繁体   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