Sunday 24 March 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...