ron*_*meh 7 javascript jquery floating-point-precision knockout.js
我面临以下场景的JavaScript的Math.floor函数问题:
1)从8192和10484的值,
if I type 8192.8 -> The Math.floor converts it into 8192.79
if I type 8192.88 -> The Math.floor converts it into 8192.87
if I type 8192.3 -> The Math.floor converts it into 8192.29
Run Code Online (Sandbox Code Playgroud)
奇怪的是,除了上面给出的范围外,该功能运行正常.
HTML:
<div data-bind="text: popIncrease"></div>
<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
Javascript:
var ViewModel = function () {
var _self = this;
_self.userInput = ko.observable();
_self.popIncrease = ko.computed(function () {
return parseFloat((Math.floor(_self.userInput() * 100) / 100)).toFixed(2);
});
};
ko.applyBindings(new ViewModel());
Run Code Online (Sandbox Code Playgroud)
jsfiddle:https://jsfiddle.net/91z5bdy4/1/
当我用1000改变100它解决了错误但我不明白为什么这发生在第一个地方?
在我看来,你的楼层/解析的顺序似乎不正常。
尝试:
return Math.floor(parseFloat(_self.userInput())).toFixed(2);
Run Code Online (Sandbox Code Playgroud)
尽管请注意,使用上述方法 1.999999999999999999999999999999 给出 2.00;这是因为浮点数无法精确表示所有值。