What is the float point rounding error in Javascript

Description

Floating-point values are not as accurate as whole numbers in arithmetic computations.

For instance, adding 0.1 and 0.2 yields 0.30000000000000004 instead of 0.3.

These small rounding errors make it difficult to test for specific floating-point values.

Example


var a = 0.1;
var b = 0.2;
console.log(a + b);/* w w  w. j a v a 2 s  .c o  m*/
if (a + b == 0.3){        
    console.log("You got 0.3.");
}

a = 0.05;
b = 0.25;
console.log(a + b);
if (a + b == 0.3){       
    console.log("You got 0.3.");
}

The code above generates the following result.

Note

You should avoid testing for specific floating-point values.

The rounding errors are a side effect of IEEE-754-based numbers.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions