Decimal home approximation in Javascript

Asked

Viewed 288 times

8

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

I am running Javascript in the console and is 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
  • What behavior?

  • The 3.3 trillion trillion instead of 3.3... @Miguelneto

2 answers

3

This is due to floating-point accuracy errors, since it is not possible to map 1.1 to a finite binary value. A similar issue can be seen here.
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.

2

Number is a javascript function that converts the string to a floating point value Note that within parentheses there is .(dot), then the string within parentheses is converted to floating point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.