-3

How are floating point numbers handled in python. I am using a simple telegram bot.

import telegram

value=0.0000023
bot.send_message(chat_id=chat_id, text=value)

I am getting 2.3e-06. Even print also gives 2.3e-06. How do I get 0.0000023. How can I handle decimal values out to at least 20 zeros.

Naren
  • 49
  • 1
  • 8
  • 2
    2.3e-06 and 0.0000023 are the same number. If you care about exact sequences of characters, it may be more appropriate to use a type that represents sequences of characters (`str`), rather than a type that represents numbers (`float`). – user2357112 supports Monica May 10 '18 at 17:18
  • Possible duplicate of [print float to n decimal places including trailing 0's](https://stackoverflow.com/questions/8568233/print-float-to-n-decimal-places-including-trailing-0s) – internet_user May 10 '18 at 17:32

1 Answers1

2

So you can just use format and specify that you want 20 decimal places but that will be pretty ugly.

>>> format(2.3e-06, ".20f")
'0.00000230000000000000'

But what you can do is use that string and then clean up all of the zeros on the right side using rstrip

>>> format(2.3e-06, ".20f").rstrip("0")
'0.0000023'
>>> format(2.3e-16, ".20f").rstrip("0")
'0.00000000000000023'

Then the only thing left is to figure out if a number is less than 10^-20 and if it is then just print it using the normal exponential formatting that Python will do anyway.

def format_for_up_to_n_decimal_places(num, n_decimal_places):
    if num < 10**-n_decimal_places:
        return str(num)
    else:
        return format(num, ".{}f".format(n_decimal_places)).rstrip('0')

Example:

>>> format_for_up_to_n_decimal_places(2.3e-6, 20)
'0.0000023'
>>> format_for_up_to_n_decimal_places(2.3e-50, 20)
'2.3e-50'
Nick Chapman
  • 3,720
  • 18
  • 34