I'm trying to format a variable to have a specific format 0000.00 currently my variable is be returned as 1.00 and want to get 0001.00
Any help would be greatly appreciated!
I'm trying to format a variable to have a specific format 0000.00 currently my variable is be returned as 1.00 and want to get 0001.00
Any help would be greatly appreciated!
Here is a really short function to do what you want:
function formatNum(num) {
return ('0000'+num.toFixed(2)).slice(-7);
}
I touched on this topic once and have this function laying around. Perhaps that is of use for you. Just call the function with your number and the digits you want.
function pad(num, digits) {
var padding = '';
var numdigits = num.toString();
var parts = numdigits.split(".");
if (parts[1].length < 2) {
numdigits = numdigits + "0";
}
if (numdigits.length > digits) {
warning("length number is longer than requested digits");
return;
} else {
for (var i = 0; i < digits; i++) {
padding += "0";
}
var numstr = padding + numdigits;
numstr = numstr.substr(numdigits.length);
return numstr;
}
}
call:
pad(1.50, 6);
result "001.50"
I use a similar method for integers, but i assume you are dealing with a string as javascript return 1.00 as 1
function pad(num, size) {
var f=num.split(".");
while (f[0].length < size) f[0] = "0" + f[0];
return f[0]+f[1];
}