js计算丢失精度问题

JS 丢失精度的问题在网上一搜一大片,所以我就找了一个使用

js计算丢失精度问题
Number.prototype.mul = function (a) {
    var b = 0, c = this.toString(), d = a.toString();
    try { b += c.split(".")[1].length } catch (e) {}
    try { b += d.split(".")[1].length } catch (e) {}
    return Number(c.replace(".", "")) * Number(d.replace(".", "")) / Math.pow(10, b)
}, Number.prototype.divide = function (a) {
    var d, e, b = 0, c = 0;
    try { b = this.toString().split(".")[1].length } catch (f) {}
    try { c = a.toString().split(".")[1].length } catch (f) {}
    return d = Number(this.toString().replace(".", "")), e = Number(a.toString().replace(".", "")), d / e * Math.pow(10, c - b)
}, Number.prototype.add = function (a) {
    var b, c, d;
    try { b = a.toString().split(".")[1].length } catch (e) { b = 0 }
    try { c = this.toString().split(".")[1].length } catch (e) { c = 0 }
    return d = Math.pow(10, Math.max(b, c)), (a * d + this * d) / d
}, Number.prototype.subtract = function (a) {
    var b, c, d, e;
    try { b = this.toString().split(".")[1].length } catch (f) { b = 0 }
    try { c = a.toString().split(".")[1].length } catch (f) { c = 0 }
    return d = Math.pow(10, Math.max(b, c)), e = b >= c ? b : c, Number(((this * d - a * d) / d).toFixed(e))
};
js计算丢失精度问题

在这个代码中 add和subtract方法 在返回操作时仍然使用的浮点计算的,所以依然会出现精度丢失的情况。

add方法

return d = Math.pow(10, Math.max(b, c)), (a * d + this * d) / d

这个记的地方应该是改为 return d = Math.pow(10, Math.max(b, c)), (a.mul(d) + this.mul(d)) / d

同样subtract这个地方也存在同样的问题。

修改后的全部代码为

js计算丢失精度问题
Number.prototype.mul = function (a) {
    var b = 0, c = this.toString(), d = a.toString();
    try { b += c.split(".")[1].length } catch (e) {}
    try { b += d.split(".")[1].length } catch (e) {}
    return Number(c.replace(".", "")) * Number(d.replace(".", "")) / Math.pow(10, b)
}, Number.prototype.divide = function (a) {
    var d, e, b = 0, c = 0;
    try { b = this.toString().split(".")[1].length } catch (f) {}
    try { c = a.toString().split(".")[1].length } catch (f) {}
    return d = Number(this.toString().replace(".", "")), e = Number(a.toString().replace(".", "")), d / e * Math.pow(10, c - b)
}, Number.prototype.add = function (a) {
    var b, c, d;
    try { b = a.toString().split(".")[1].length } catch (e) { b = 0 }
    try { c = this.toString().split(".")[1].length } catch (e) { c = 0 }
    return d = Math.pow(10, Math.max(b, c)), (a.mul(d) + this.mul(d)) / d
}, Number.prototype.subtract = function (a) {
    var b, c, d, e;
    try { b = this.toString().split(".")[1].length } catch (f) { b = 0 }
    try { c = a.toString().split(".")[1].length } catch (f) { c = 0 }
    return d = Math.pow(10, Math.max(b, c)), e = b >= c ? b : c, Number(((this.mul(d) - a.mul(d)) / d).toFixed(e))
};
js计算丢失精度问题

js计算丢失精度问题

上一篇:.net 4.0 异步读取数据用法


下一篇:Asp.Net MVC中DropDownListFor的用法