1

I have a multiple in python 3.7.3 when I run 0.58 * 100 it return 57.99999999999999

Then I found that Java have same result. But C can return right number. I don't know what happen with them. Sorry if it look like basic.

haulpd
  • 257
  • 2
  • 6
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – mkrieger1 Dec 08 '21 at 11:19

1 Answers1

2

Its actually not the wrong answer, just an unexpected one.

If we think a bit about the problem, There are an infinite amount of numbers between 0 and 1. Then we can see that you cannot represent all numbers between 0 and 1 with a finite amount of bytes, as infinite numbers are more then a finite number of numbers. so some numbers just cant be represented (in fact, most numbers of the infinite series between 0 and 1 cannot be represented)

Following the floating point standard (IEEE-754), 0.58 is really 0.5799999999999999289457264239899814128875732421875 which is the closest number to 0.58 that can be represented with 64bit floating points.

check it with python

>>> Decimal(0.58)
Decimal('0.57999999999999996003197111349436454474925994873046875')

If you want 58.0 you can quantize it to two decimals with the Decimal class.

>>> Decimal(100 * 0.58).quantize(Decimal('.01'))
Decimal('58.00')
krs
  • 4,096
  • 19
  • 22