Skip to content

Instantly share code, notes, and snippets.

@willread
Created August 21, 2012 15:29
Show Gist options
  • Save willread/3416587 to your computer and use it in GitHub Desktop.
Save willread/3416587 to your computer and use it in GitHub Desktop.
Pad a number with leading zeros to a specified length
var padNumber = function(n, d){
if(!d || d <= (n+"").length)
return n+"";
return (0).toPrecision(d - (n+"").length).replace(".", "")+n;
}
padNumber(1.234, 6); // Returns "000001.234"
padNumber(1.234, 10); // Returns "01.234"
padNumber(1.234, 3); // Returns "1.234"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment