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.
精彩评论