简体   繁体   中英

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

JavaScript doesn't have different types for integers and floating point numbers. When working with "integers", does this mean I need to worry about round-off error?

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

x % 3 == 0

or do I need to do a floating-point-style compare such as:

x % 3 <= 0.5

Any insight would be appreciated.

(If I do need to do the inequality there, what about checking if a passed argument to a function is equal to 1; can I write x === 1 or not?)

If you're working with integers, it is usually safe. However, some floating-point arithmetic can act very strangely. If you perform floating-point operations on the number before using modulus, even if the logical result will always be an integer, you should use:

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

But if it's always an integer, like this:

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

Then that's fine. In regards to your second question, the === identity operator is also safe to use between numbers. For example:

function x(y) {
    return y === 7;
}

alert(x(7.0)); // true

Works correctly.

if x is an integer, you can do the modulus as written first.

and '===' is only necessary if you want to fail, say, a string "1" or boolean true, but pass an integer 1; otherwise '==' should be sufficient.

JavaScript doesn't expose different types for ints and floats, but does have the concept of them. the built-in function parseInt can be used to force a number (or any other number-like value, including the string "32.06".) to be an integer, It truncates, rather than rounding. floating-point values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM