Question

Python's arbitrary precision decimals are lovely, but I can't seem to find a way to print them in a nicely formatted way. For example, if I compute the following expression:

>>> pow(2,70) -2
1180591620717411303422L

it ends in a 2, like it should. However, if I try to format it to show two decimal places, it gets rounded to 2^70 because floats aren't very precise.

>>> print "{0:.2f}".format(pow(2,70) -2)
1180591620717411303424.00

Is there a way to print with the formatting I want without losing precision?
(and without using any non-standard modules such as NumPy)

Was it helpful?

Solution

This works for me:

>>> import decimal
>>> '{0:.2f}'.format(decimal.Decimal((pow(2,70)-2)))
1180591620717411303422.00

From the decimal module documentation:

The decimal module provides support for decimal floating point arithmetic. [...] Decimal numbers can be represented exactly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top