简体   繁体   English

我什么时候需要担心 JavaScript 中的浮点错误?

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

JavaScript doesn't have different types for integers and floating point numbers. JavaScript 对于整数和浮点数没有不同的类型。 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 整除,可以这样写吗

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?) (如果我确实需要在那里做不等式,那么检查传递给 function 的参数是否等于 1;我可以写x === 1吗?)

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:如果您在使用模数之前对数字执行浮点运算,即使逻辑结果始终是 integer,您也应该使用:

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

But if it's always an integer, like this:但如果它总是一个 integer,像这样:

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.如果 x 是 integer,您可以按照先写的方式计算模数。

and '===' is only necessary if you want to fail, say, a string "1" or boolean true, but pass an integer 1;并且 '===' 仅在您想要失败时才需要,例如字符串“1”或 boolean 为真,但通过 integer 1; otherwise '==' should be sufficient.否则'=='就足够了。

JavaScript doesn't expose different types for ints and floats, but does have the concept of them. JavaScript 没有为整数和浮点数公开不同的类型,但确实有它们的概念。 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.内置的 function parseInt可用于强制数字(或任何其他类似数字的值,包括字符串“32.06”。)为 integer,它截断而不是舍入。 floating-point values.浮点值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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