简体   繁体   中英

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

If the value of the thousandths place is between .001 and .004 then round up to .005

If the thousands place is between .006 and .009 then round to .010 and do not drop the zero.

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)

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 ).
The + 0.005 is to make it round up as desired, otherwise it would always round down.
toFixed() is used to make the string representation of the value have the decimal part padded with zeros as needed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM