0
Is there any way I can automatically round a number to the nearest hundredth instead of the nearest integer?
5 Respuestas
+ 8
Yeah,
var num = 5.345;
var n = num.toFixed(2);
n is now 5.35
+ 6
var test = 512
var r100 = 100*Math.round(test/100);
+ 6
@Helioform:
:D
So much simple, that I have complexified by missunderstanding ^^
+ 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.
+ 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