0

Why this will not give the results as expected?

console.log(0.2+0.1); // gives 0.30000000000000004 
console.log(0.2+0.3); // gives 0.5
console.log(0.2+0.5); // gives 0.7
console.log(0.2+0.4); // gives 0.6000000000000001 

Why the first and last will not give the results as expected?

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106

2 Answers2

1

It’s because JavaScript used the IEEE Standard for Binary Floating-Point Arithmetic.

All floating point math is like this and is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double.

Can be possible duplicate of Is floating point math broken?

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Try .toFixed() .This method formats a number with a specific number of digits to the right of the decimal.

console.log((0.2 + 0.1).toFixed(1)); // gives 0.3
console.log((0.2 + 0.3).toFixed(1)); // gives 0.5
console.log((0.2 + 0.5).toFixed(1)); // gives 0.7
console.log((0.2 + 0.4).toFixed(1)); // gives 0.6
Devang Rathod
  • 6,650
  • 2
  • 23
  • 32
  • Thanks Devang, I know about `toFixed` method. I wanted to know what is the reason behind this `unexpected result`. – Rohan Kumar Mar 25 '13 at 12:33