I can round to x amount of decimal places with math.round but is there a way to round left of the decimal? for example 5 becomes 05 if I specify 2 places
+5
A:
You're asking for zero padding? Not really rounding. You'll have to convert it to a string since numbers don't make sense with leading zeros. Something like this...
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Or if you know you'd never be using more than X number of zeros this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the "-" and readd it.
InfinitiesLoop
2010-06-08 15:33:07
+6
A:
Another approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
CMS
2010-06-08 15:39:09
+1 - I was going to suggest the array joining method until InfinitiesLoop posted his answer and I changed my mind :-)
Andy E
2010-06-08 15:43:44
You're not taking into account negative array sizes ;) eg `zeroPad(1234, 2)` -> `RangeError: Invalid array length`
Crescent Fresh
2010-06-08 15:59:26
@Crescent: Thanks, fixed...
CMS
2010-06-08 16:07:57
A:
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...
Christoph
2010-06-08 16:35:12