Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round off decimal using javascript

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..

like image 363
Prasad Avatar asked Apr 04 '11 06:04

Prasad


People also ask

How do you round off decimals in JavaScript?

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

How do I round to 2 decimal places in JavaScript?

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.

How do you round to 3 decimal places in JavaScript?

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.


2 Answers

(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);
}
like image 166
ayk Avatar answered Nov 01 '22 12:11

ayk


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.

like image 2
eve Avatar answered Nov 01 '22 11:11

eve