Sunday, March 24, 2019

Javascript always round up to X decimal places




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?


Answer



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




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...