0

I’m trying to get a more precise result from this code:

a = str(10**20+10**-20)
b = eval(a)

I want to obtain around 42 decimal places so Python doesn’t round it to 1e+20.

  • Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – henrywongkk Oct 04 '19 at 01:54

1 Answers1

1

You actually 'only' need 41 to accomplish that. Use the decimal module:

import decimal
decimal.getcontext().prec=41
a = 10**20+10**decimal.Decimal(-20)

Python's floating-point types are just as inaccurate as in any other language. The decimal module contains the Decimal data structure, capable of handling arbitrarily long decimal numbers instead. You can read more about it here: check it out.

Michele Bastione
  • 363
  • 3
  • 13
  • Your comment on my post is correct. I removed it to deter potential confusion and upvoted yours. – Shmack Nov 30 '22 at 22:14