my_number = 42379943902701922
print(my_number * 10**-18)
Expected output: 0.042379943902701922
Actual output: 0.04237994390270192
Actual output is missing one 2 at the end. Why is that so and how can I arrive at the expected output?
my_number = 42379943902701922
print(my_number * 10**-18)
Expected output: 0.042379943902701922
Actual output: 0.04237994390270192
Actual output is missing one 2 at the end. Why is that so and how can I arrive at the expected output?
In addition to Decimal
, you can use the BigFloat
library for precise decimal numbers. Example:
from bigfloat import *
precise_number = BigFloat('0.042379943902701922', precision(18))
Alternatively, to do the calculation:
with precision(18) + RoundTowardZero:
print(BigFloat.exact(my_number * 10**-18))
By default, Python interprets any number that includes a decimal point as a double-precision floating point number. However, you can bypass that by using the decimal module, which provides support for correctly rounded decimal floating point arithmetic.
Example:
getcontext().prec = 28
Decimal(1) / Decimal(7)
Output:
Decimal('0.1428571428571428571428571429')
Thats how its getting printed in console/terminal. You can convert to string while printing if you want to see all the digits
# How it gets printed
>>> print(my_number * 10**-18)
0.04237994390270192
# How its stored
>>> my_number
42379943902701922
# How to print all the digits
>>> print(str(my_number))
42379943902701922
# Or with repr
>>> repr(my_number)
'42379943902701922'