I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
JavaScript Math.round() The Math.round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.
Use the toFixed() method to round a number to 3 decimal places, e.g. num. toFixed(3) . The toFixed method formats a number to a specified number of decimal places and rounds the number if necessary.
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);
If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)
And now as function:
function trueRound(value, digits){
return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}
Thanks @ayk for your answer, I modified your function into this :
function trueRound(value, digits){
return ((Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits)) * 1;
}
just add " *1 " because with yours, as you wrote, 16.2 becomes 16.20 and I don't need the zero in the back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With