JavaScript decimal approximation [duplicate]

8

What is the reason for the behavior below? Why not 3.3?

I am running the JavaScript console and are returning this result.

Number(1.1)
1.1

Number(1.1) + Number(1.1)
2.2

Number(1.1) + Number(1.1) + Number(1.1)
3.3000000000000003

Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1)
4.4

Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1) + Number(1.1)
5.5
    
asked by anonymous 12.11.2015 / 20:45

2 answers

3

This happens because of floating-point precision errors, since it is not possible to map 1.1 to a finite binary value. A similar issue can be seen here . Home This behavior can be changed through the toFixed () function.
Example:

(1.1 + 1.1 + 1.1).toFixed(2)

2 being the number of decimal places.

    
12.11.2015 / 22:37
2

Number is a javascript function that converts the string to a floating-point value See that inside the parenthesis has (dot), then the string inside the parentheses is converted to floating point.

    
12.11.2015 / 20:48