简体   繁体   English

Knockout.Validation中的浮点舍入错误

[英]Floating point rounding errors in Knockout.Validation

I have an numeric input with a step of 0.01 that is "watched" by Knockout and has the Knockout.validation plugin also checking the value. 我有一个数字输入,步长为0.01,被Knockout“监视”,并且Knockout.validation插件也检查该值。

When testing the input to make sure that it is giving appropriate error messages, I found that certain input will result in a validation message. 在测试输入以确保它给出适当的错误消息时,我发现某些输入将导致验证消息。 For example, the value -0.14 will result in the error: "The value must increment by 0.01". 例如,值-0.14将导致错误:“该值必须增加0.01”。

The offending Knockout.Validation code is: 令人讨厌的Knockout.Validation代码为:

return utils.isEmptyVal(val) || (val * 100) % (step * 100) === 0;

For val = -0.14 with step = 0.01 , floating point arithmetic causes this line to return false, meaning that Knockout.Validation sees -0.14 as an invalid input. 对于val = -0.14step = 0.01 ,浮点算法使该行返回false,这意味着Knockout.Validation将-0.14视为无效输入。 This is just an example, there are many cases where this happens. 这只是一个例子,在很多情况下会发生这种情况。 For the -0.14 case, the result of (val * 100) % (step * 100) is -1.7763568394002505e-15 . 对于-0.14情况, (val * 100) % (step * 100)-1.7763568394002505e-15

Is there an easy way I can patch this code? 有没有简单的方法可以修补此代码? Would the following suffice under all circumstances: 在所有情况下,以下内容是否足够:

return utils.isEmptyVal(val) || parseInt(val * 100) % parseInt(step * 100) === 0;

Or should I have a range check? 还是应该进行范围检查?

In a similar situation, I found the code in this issue fixed my problem. 在类似的情况下,我发现此问题中的代码解决了我的问题。

The core code in question seems very similar to your proposed solution, although I assume there is a good reason to use parseFloat rather than parseInt. 尽管我认为有充分的理由使用parseFloat而不是parseInt,但所讨论的核心代码似乎与您提出的解决方案非常相似。

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

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