Question

I'm interested in displaying a decimal number to 100 decimal places. Here is what I come up so far. As can be seen, this is not quite what I wanted. ex. 1/3 should have 3's repeated to the end.

Is there a way to accomplish this in Python?

>>> x = 1./3
>>> "%.100f" % x
'0.3333333333333333148296162562473909929394721984863281250000000000000000000000000000000000000000000000'
>>> y = 1./7
>>> "%.100f" % y
'0.1428571428571428492126926812488818541169166564941406250000000000000000000000000000000000000000000000'
Was it helpful?

Solution

Use the decimal module.

>>> import decimal
>>> decimal.getcontext().prec = 100
>>> decimal.Decimal(1) / decimal.Decimal(3)
Decimal('0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333')

OTHER TIPS

The issue you're encountering is that floating point numbers have limited precision. If you want more than that, you need to use a different data type. I'd suggest investigating the decimal module, which can support arbitrarily large precisions.

>>> x = 1./3
>>> str(x).ljust(100, '0')
'0.33333333333300000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
import decimal
decimal.getcontext().prec = 10000000
print(decimal.Decimal(22) / decimal.Decimal(7))

Now you can increase the prec value and get to whatever decimal value you like.

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