When do I need to worry about a floating point error in JavaScript?

JavaScript does not have different types for integers and floating point numbers. When dealing with "integers" does this mean that I need to worry about rounding errors?

For example, if I want to know when the number x is divisible by 3, is it possible to write

 x % 3 == 0 

or I need to do a floating point comparison, for example:

 x % 3 <= 0.5 

Any insight would be appreciated.

(If I need to make an inequality there, how about checking if the passed function argument is 1, can I write x === 1 or not?)

+4
source share
3 answers

If you work with integers, this is usually safe. However, some floating point arithmetic operations can be very strange. If you perform floating point operations on a number before using the module, even if the logical result is always an integer, you should use:

 Math.floor(x) % 3 === 0 

But if it is always an integer, for example:

 var x = 52; if(x % 3 === 0) { // safe } 

Then it’s wonderful. As for your second question, the identification operator === also safe to use between numbers. For instance:

 function x(y) { return y === 7; } alert(x(7.0)); // true 

Works correctly.

+4
source

if x is an integer, you can make the module as written first.

and '===' are necessary only if you want to fail, say, the string "1" or the logical value true, but pass the integer 1; otherwise '==' should be enough.

+1
source

JavaScript does not provide different types for int and floats, but has a concept for them. parseInt built-in function can be used to force a number (or any other numeric value, including the string "32.06"!) as an integer. It truncates, rather than rounds, floating point values.

0
source

All Articles