1

I have a string that I need to convert to a float for me to work on.

num = "2.769999999999999574e+00"

If I do a float operation, the precision is gone

print(float(num))  # 2.7699999999999996

If I use a Decimal class ,even then the precision is gone

from decimal import Decimal
print(Decimal(num))  # 2.769999999999999574

It seems Decimal is only able to retain the precision if the number supplied is a float in the first place

print(Decimal(2.769999999999999574e+00))  # 2.769999999999999573674358543939888477325439453125

How do I maintain precision while converting a number from string to float?

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70
  • What do you mean by "the precision is gone"? You convert the number `2.769999999999999574` to decimal and get `2.769999999999999574`. What do you expect? – user202729 Mar 04 '18 at 08:05
  • [No, converting that to float doesn't lose any precision](https://tio.run/##K6gsycjPM/7/P680V8FWQclIz9zMEhmYmpukahsYKHEVFGXmlWioV1vpmRrUquul5RflJpZopOXkA0mgZk1Nzf//AQ). They're just not displayed. – user202729 Mar 04 '18 at 08:08
  • @user202729 updated the code.Here 2.769999999999999574e+00 is a very large number and I want to keep it as large as I can possibly keeping the 'e' notation.Currently only Decimal is able to give me a very large number but only when the given number is not a string. – Souvik Ray Mar 04 '18 at 08:10
  • Are you sure about that? The exponent is e00. – cs95 Mar 04 '18 at 08:11
  • @cᴏʟᴅsᴘᴇᴇᴅ I only took one of the numbers as an example.There are numbers with with e02 and so on. – Souvik Ray Mar 04 '18 at 08:13

1 Answers1

1

Decimal(2.769999999999999574e+00) doesn't "retain precision". It only exposes the limitations of floating point arithmetic. The number you specify does not have an exact bit representation in memory, and is approximated to some degree, accounting for the extended precision you see here. This is a limitation of your (and any other) CPU. Decimal("2.769999999999999574e+00") on the other hand, is actually a more correct representation of your quantity than passing an actual float.

cs95
  • 379,657
  • 97
  • 704
  • 746