Robb1
Robb1

Reputation: 5025

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?

Upvotes: 0

Views: 123

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118011

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')

Upvotes: 4

Related Questions