Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript always round up to X decimal places [duplicate]

Tags:

javascript

I need to write a function that will ALWAYS round up, but will either round up to 0, 1 or 2 decimal places, depending on if the function is passed a 0, 1 or 2.

Examples...

Round to 0 decimal places: 13.4178 = 14

Round to 1 decimal place: 13.4178 = 13.5

Round to 2 decimal places: 13.4178 = 13.42

I've found Math.ceil but this only rounds up to a whole integer and to fixed() will round up or down, not just up. Is there a way to round up in the way I've described above?

like image 653
Janey Avatar asked Dec 06 '25 03:12

Janey


1 Answers

You could use a factor for multiplication with ten and the power of the wanted decimal count and then round it and adjust the dot.

function up(v, n) {
    return Math.ceil(v * Math.pow(10, n)) / Math.pow(10, n);
}

console.log(up(13.4178, 0));
console.log(up(13.4178, 1));
console.log(up(13.4178, 2));
like image 84
Nina Scholz Avatar answered Dec 07 '25 16:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!