的预期结果:
(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18但在JS中显示:
(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*如何纠正这一问题?
发布于 2014-01-13 12:56:19
您可以尝试使用圆形,而不是toFixed。
Math.round(5.175*100)/100
如果你愿意的话,你甚至可以尝试把它放到原型方法中。
创建了一个jsBin,它实现了一个简单的数字原型。
Number.prototype.toFixed = function(decimals) {
return Math.round(this * Math.pow(10, decimals)) / (Math.pow(10, decimals));
};发布于 2014-01-13 12:54:14
这不是窃听器。这与数字不是用十进制存储,而是在IEEE754中存储的事实有关(所以5.175没有被准确地存储)。
如果您想在一个特定的方向(向上)旋转,并且始终具有此精度的数字,则可以使用以下技巧:
(5.175 + 0.00001).toFixed(2)发布于 2014-05-29 14:36:04
这是因为数字存储为IEEE754。
我建议您使用数学类(圆形、地板或ceil方法,视需要而定)。
我刚刚创建了一个类MathHelper,它可以轻松地解决您的问题:
var MathHelper = (function () {
this.round = function (number, numberOfDecimals) {
var aux = Math.pow(10, numberOfDecimals);
return Math.round(number * aux) / aux;
};
this.floor = function (number, numberOfDecimals) {
var aux = Math.pow(10, numberOfDecimals);
return Math.floor(number * aux) / aux;
};
this.ceil = function (number, numberOfDecimals) {
var aux = Math.pow(10, numberOfDecimals);
return Math.ceil(number * aux) / aux;
};
return {
round: round,
floor: floor,
ceil: ceil
}
})();用法:
MathHelper.round(5.175, 2)演示:http://jsfiddle.net/v2Dj7/
https://stackoverflow.com/questions/21091727
复制相似问题