欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js運算精度丟失的2個解決方法

 更新時間:2023年06月08日 15:13:24   作者:AJiu~~  
近期在做項目的時候,遇到了一些JS浮點數(shù)精度的問題,這個問題其實說大不大,說小不小,下面這篇文章主要給大家介紹了關于js運算精度丟失的2個解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

當兩個數(shù)包含小數(shù)進行運算的時候結果并不是正確的結果,而是出現(xiàn)了精度丟失的情況(小數(shù)點后面出現(xiàn)很多位)。

問題所在:

 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 )

        參數(shù):此函數(shù)參數(shù)列表有一個參數(shù),他表示小數(shù)點后面精確的位數(shù)。

       返回值:他以字符串表示形式返回一個數(shù)字。

代碼實現(xiàn):

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);
});

界面顯示:

小結:

該解決方法只適用于低精度運算。并且有弊端,就如上圖界面顯示一樣,最終運算結果是沒有小數(shù)位的,還是將小數(shù)位給顯示出來的。如果不在乎這些還是可以使用的。

解決方法2(高精度):

先將運算值 x 10^n 轉換成整數(shù)進行運算,最后將結果還原。精度要求高的推薦使用該解決方法。(代碼實現(xiàn)只實現(xiàn)了乘法,需要其他運算的可以自行更改一下)

代碼實現(xià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);

輸出結果:

小結:

該解決方法適用于高精度運算,既解決了精度丟失問題,又解決了我想要的最終結果是整數(shù)不顯示小數(shù)位的問題。如果要求高精度請選擇該解決方案。

到此這篇關于js運算精度丟失的2個解決方法的文章就介紹到這了,更多相關js運算精度丟失內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論