0


js运算精度丢失

当两个数包含小数进行运算的时候结果并不是正确的结果,而是出现了精度丢失的情况(小数点后面出现很多位)。

问题所在:

 res.orderColorDeliveryRecords.forEach((item) => {
                        //计算金额
                        item.money = (item.price * item.amount);
                        if(!item.cusTypeName){
                            item.cusTypeName = 'N/A';
                        }
                        this.record.money += parseFloat(item.money);
                    });

界面显示:

解决方法1(低精度):

在运算结果的后面加上toFixed(),精度要求不高的情况下使用;

toFixed介绍:

    **用法:** *number*.toFixed( value )

** 参数:**此函数参数列表有一个参数,他表示小数点后面精确的位数。

   **返回值:**他以字符串表示形式返回一个数字。

代码实现:

res.orderColorDeliveryRecords.forEach((item) => {
    item.money = this.actionOperationResult(item.price , item.amount);

    
    if(!item.cusTypeName){
        item.cusTypeName = 'N/A';
    }
    this.record.money += parseFloat(item.money);
});

界面显示:

小结:

该解决方法只适用于低精度运算。并且有弊端,就如上图界面显示一样,最终运算结果是没有小数位的,还是将小数位给显示出来的。如果不在乎这些还是可以使用的。

解决方法2(高精度):

    先将运算值 x 10^n 转换成整数进行运算,最后将结果还原。精度要求高的推荐使用该解决方法。(代码实现只实现了乘法,需要其他运算的可以自行更改一下)

代码实现:


actionOperationResult(val1, val2){
    const p = this.actionOperation(val1, val2);
    return ((val1 * p) * (val2 * p)) / (p * p);
},

actionOperation(val1, val2){
    const len1 = val1.toString().length - val1.toString().indexOf(".") - 1;
    const len2 = val2.toString().length - val2.toString().indexOf(".") - 1;
    const p = Math.max(len1, len2);
    // 避免最终求出结果的长度大于最大长度的时候导致精度丢失 开启下面
    // p += p - Math.min(len1, len2); 
    return  Math.pow(10, p);
}

测试1:

item.money = this.actionOperationResult(item.price , item.amount);     

界面显示:

测试2:

const test  = this.actionOperationResult(123.456789435252 , 42.697894);
const test1  = this.actionOperationResult(4342.57897 , 64789.337489);
const test2  = this.actionOperationResult(78.7897398 , 67.768978943);
console.log("test:",test);
console.log("test1:",test1);
console.log("test2:",test2);

输出结果:

小结:

该解决方法适用于高精度运算,既解决了精度丢失问题,又解决了我想要的最终结果是整数不显示小数位的问题。如果要求高精度请选择该解决方案。


本文转载自: https://blog.csdn.net/ZWP_990527/article/details/128109063
版权归原作者 AJiu~~ 所有, 如有侵权,请联系我们删除。

“js运算精度丢失”的评论:

还没有评论