2

Today I have entered random float number and multipled by hundred firstly using normal code and then in console as was giving me wrong number, console is returning me the same.

The given float number is: 1050.6

Therefore: 1050.6 * 100 should be 105060, but javascript is returning me 105059.99999999999

Anyone knows why?

Marek
  • 440
  • 2
  • 6
  • 18
  • 5
    See this question: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Retsam Jun 18 '15 at 22:26

2 Answers2

3

JavaScript uses 64-bit floating point representation (double precision). Numbers are represented in this format as a whole number multiplied by a power of two.

This is based on the IEEE 754 standard

Rational numbers with a denominator that isn't a power of 2 can't be exactly represented. This is why floating point multiplication gives this result.

Source: https://en.wikipedia.org/wiki/IEEE_floating_point

If you want to get the real value, there are two methods you can use

Rounding with Math.round

Math.round(1050.6 * 100)

Or toFixed

(1050.6 * 1000).toFixed(0)
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

It's a feature of how computers handle floating point numbers. It turns out that decimal numbers can't always be perfectly represented in binary so the computer gives the closest approximation it can.

https://en.wikipedia.org/wiki/IEEE_floating_point

Hath995
  • 821
  • 6
  • 12