简体   繁体   English

如何在JavaScript中四舍五入并保持小数点后的位数

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

If .950 display .950 If .954 display .955 If .956 display .960 如果.950显示.950如果.954显示.955如果.956显示.960

If the value of the thousandths place is between .001 and .004 then round up to .005 如果千分之一位的值在.001和.004之间,则四舍五入为.005

If the thousands place is between .006 and .009 then round to .010 and do not drop the zero. 如果千位在.006和.009之间,则四舍五入为.010,并且不要丢弃零。

Brutally: 残酷地:

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"

Pay attention : function returns a string ( .toFixed returns a string).. (but however a fixed decimal length doesn't have any sense in a number) 注意 :函数返回一个字符串( .toFixed返回一个字符串)..(但是固定的十进制长度在数字上没有任何意义)

Rounding to a certain number of decimals is done by multiplying the value to bring the desired amount of decimals into the integer range, then getting rid of the remaining decimals, then dividing by the same multiplier to make it decimal again. 通过将值乘以使所需的小数位数进入整数范围,然后去除剩余的小数位数,然后除以相同的乘数再使其变为小数位数,可以舍入到小数位数。
Rounding to a "half-decimal" as you want is accomplished by doubling the multiplier ( 2X instead of 1X ). 通过将乘数加倍( 2X而不是1X ),可以根据需要舍入到“半小数”。
The + 0.005 is to make it round up as desired, otherwise it would always round down. + 0.005用于根据需要将其四舍五入,否则将始终四舍五入。
toFixed() is used to make the string representation of the value have the decimal part padded with zeros as needed. 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