简体   繁体   中英

How to avoid rounding for long decimal numbers in Python?

I would like to print the first 200 decimal digits of the number 1/998,001 . If I run the following code

print("{:10.200f}".format(1/998001))

the result I obtain is rounded

0.00000100200300400500595528706631459625597813101194333285093307495117187500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

How can I obtain the precise result instead?

You can use the decimal module for this

import decimal
with decimal.localcontext() as ctx:
    ctx.prec = 200
    d = decimal.Decimal(1.0) / 998001

>>> d
Decimal('0.0000010020030040050060070080090100110120130140150160170180190200210220230240250260270280290300310320330340350360370380390400410420430440450460470480490500510520530540550560570580590600610620630640650660671')

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