Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output numbers with leading zeros in JavaScript? [duplicate]

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

like image 993
chris Avatar asked Jun 08 '10 15:06

chris


People also ask

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you add leading zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.


1 Answers

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {     num = num.toString();     while (num.length < size) num = "0" + num;     return num; } 

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 read it.

like image 125
InfinitiesLoop Avatar answered Sep 28 '22 20:09

InfinitiesLoop