0

I was playing with Node REPL and came across this strange behavior.

4.32 + 4.78 should be just 9.1

> 4.32 + 4.78 9.100000000000001

Another one is:

> 7.3 + 1.08 8.379999999999999

For other digits it works fine:

> 4.31 + 4.78 9.09

Tested it on Node version 4.8.3 and 7.4 on Ubuntu 16.04 and Linux/amd64 respectively.

Getting the same output.

Can anyone explain why it is like this?

Kartikey Tanna
  • 1,423
  • 10
  • 24
  • 1
    it's not a node js problem it's javascript problem check all value in browser console you will get the same result exp check 2.4+2.3 = 4.699999999 – vipin kumar Jul 06 '17 at 12:54

1 Answers1

6

JavaScript uses IEEE 754 double precision floating-point numbers (see ECMA-262) and they cannot accurately represent all decimal fractions.

To get the results that you expect you can either scale the numbers to work on integers (e.g. count cents instead of dollars) or round the numbers to a specific number of decimal digits after you do the calculations.

Examples:

> 4.32 + 4.78
9.100000000000001

> (432 + 478) / 100
9.1

> +(4.32 + 4.78).toFixed(2)
9.1

> Math.round(100 * (4.32 + 4.78)) / 100
9.1

See this for more details:

rsp
  • 107,747
  • 29
  • 201
  • 177