简体   繁体   中英

Printing formatted arbitrary precision decimals in python

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM