0

Is there any way I can automatically round a number to the nearest hundredth instead of the nearest integer?

8th May 2017, 12:57 AM
Ben Galbraith
5 ответов
+ 8
Yeah, var num = 5.345; var n = num.toFixed(2); n is now 5.35
8th May 2017, 12:59 AM
Karl T.
Karl T. - avatar
+ 6
var test = 512 var r100 = 100*Math.round(test/100);
8th May 2017, 12:59 AM
visph
visph - avatar
+ 6
@Helioform: :D So much simple, that I have complexified by missunderstanding ^^
8th May 2017, 1:01 AM
visph
visph - avatar
+ 6
Note that you have to convert it back to a number with my solution with -edit, not parseInt() of course, but a function that converts a string to float.
8th May 2017, 1:05 AM
Karl T.
Karl T. - avatar
+ 5
With parseFloat(), else you will lose the decimal part ;) The main problem is that you cannot conserve a decimal value with a fixed digit number after the dot because of floating point unaccuracy... The workaround is mathematical: storing the value * 100 ( or any 10^n ), and using it with dividing it by same ten power. Anyway, almost of the time, you need to format with a fixed digit number for text output :P
8th May 2017, 1:13 AM
visph
visph - avatar