簡體   English   中英

如何在JavaScript中四舍五入並保持小數點后的位數

[英]how to round up and keep number of digits after decimal point in javascript

如果.950顯示.950如果.954顯示.955如果.956顯示.960

如果千分之一位的值在.001和.004之間,則四舍五入為.005

如果千位在.006和.009之間,則四舍五入為.010,並且不要丟棄零。

殘酷地:

function formatValue(value) {
    var tempVal = Math.trunc(value * 1000);
    var lastValue = (tempVal % 10);

    if (lastValue > 0 && lastValue <= 5) lastValue = 5;
    else if (lastValue > 5 && lastValue <= 9) lastValue = 10;
    else lastValue = 0;

    return parseFloat((Math.trunc(tempVal / 10) * 10 + lastValue) / 1000).toFixed(3);
}

formatValue(3.656); // -> "3.660"
formatValue(3.659); // -> "3.660"
formatValue(3.660); // -> "3.660"
formatValue(3.661); // -> "3.665"
formatValue(3.664); // -> "3.665"
formatValue(3.665); // -> "3.665"

注意 :函數返回一個字符串( .toFixed返回一個字符串)..(但是固定的十進制長度在數字上沒有任何意義)

通過將值乘以使所需的小數位數進入整數范圍,然后去除剩余的小數位數,然后除以相同的乘數再使其變為小數位數,可以舍入到小數位數。
通過將乘數加倍( 2X而不是1X ),可以根據需要舍入到“半小數”。
+ 0.005用於根據需要將其四舍五入,否則將始終四舍五入。
toFixed()用於使值的字符串表示形式根據需要將小數部分填充為零。

 function formatValue(value) { return (Math.floor((value + 0.005) * 200) / 200).toFixed(3); } console.log(formatValue(1.950)); console.log(formatValue(1.954)); console.log(formatValue(1.956)); console.log(formatValue(1.003)); console.log(formatValue(1.007)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM