0

I'm having an issue here. Why does the code below give out a wrong output?

test = '{:.{}f}'.format(35.72506789023292, 15)
print(test)

>> 35.725067890232921

isnt it supposed to give me this?:

>> 35.725067890232920

i tried different numbers but they also fail. How can I make this work? I read regarding floats in Python and it is stated that it give accurate decimal digits for upto 16. This example only has 15 so it should be enough for float handling.

martineau
  • 119,623
  • 25
  • 170
  • 301
shafuq
  • 465
  • 6
  • 20
  • Because with binary floating-point, what you see is *not* what you get. The value you specified as `35.72506789023292` is actually stored as `35.7250678902329212860422558151185512542724609375`. The closest 15-digits-past-the-point decimal value to that is `35.725067890232921`. – Mark Dickinson Dec 22 '17 at 15:31
  • Where did you read the "accurate decimal digits for upto 16" claim? It's at best misleading. (Also, note that the value you specify has 16 significant digits, not 15, and you're asking for 17 significant digits in the output.) – Mark Dickinson Dec 22 '17 at 15:31
  • You see, I read all of those. I also included in my question that Python documents tell us that upto 16 digits for decimals are accurate. This one has only 15. So why is it still show a wrong output? If I assign the number into a float variable and sum it with for example 0.02155454 or whatever, it does calculate the result properly. I tested all of that. The problem lays down on using the string format function. I even tried to put the number in the string format in a decimal function like '{:.{}f}'.format(Decimal(35.72506789023292), 15) but that too gave an error. – shafuq Dec 22 '17 at 15:33
  • I believe I read it in the Python documents. It stated that the float in Python (maybe it said 3, I use 3 so that's not the case) stores floats like doubles in other languages. upto 16.. I am gonna try to find it. – shafuq Dec 22 '17 at 15:34
  • I couldn't find the doc I read last night. But I did figure out a simple solution. For anyone out there looking for a solution for the example above, just use Decimal. I had tried that but it seems Decimal has to contain the number within ' ' (Didnt know that :/ ). So writing this worked: '{:.{}f}'.format(Decimal('35.72506789023292'), 15) – shafuq Dec 22 '17 at 15:50

0 Answers0