- Number with leading zero in JavaScript
- 3 Answers 3
- TL;DR
- History
- Format numbers in javascript leading zero
- # Add Leading Zeros to a Number in JavaScript
- # Padding negative numbers with leading zeros
- # Pad a number with leading zeros using the addition (+) operator
- # Pad a number with Leading Zeros using a while loop
- How to Output Numbers With Leading Zeros in JavaScript
- How to Output Numbers With Leading Zeros in JavaScript?
- Method 1: Output Numbers With Leading Zeros Using Addition Operator
- Syntax
- Example
- Method 2: Output Numbers With Leading Zeros Using padStart() Method
- Syntax
- Example
- Output
- Conclusion
- About the author
- Farah Batool
Number with leading zero in JavaScript
I have accepted your answer before, did so now again. Strange that it didn’t take the first time. Thanks again Levu.
3 Answers 3
TL;DR
It’s being treated as octal (base 8) because of the leading 0 , just like a leading 0x would make it hex (base 16). This has a long and tortured history and is no longer how octal numbers are written in modern JavaScript. In modern JavaScript using strict mode, the «legacy» octal format is a syntax error; octal numbers are written with an 0o prefix.
History
Early on (in the initial language from Netscape and the first and second ECMAScript specifications), a leading 0 on a numeric literal officially meant octal (base 8), just as a leading 0x means hexadecimal (base 16):
OctalIntegerLiteral :: 0 OctalDigit OctalIntegerLiteral OctalDigit
E.g., 10 , 012 , and 0xA were all ways of writing the decimal number ten. This is in keeping with some other languages with syntax similar to JavaScript (C, C++, Java, . ), but it’s highly confusing.
As of ECMAScript 3, that form of octal literal was downgraded to an optional extension, and decimal integer literals were changed so that they can’t have leading zeros (unless the implementation includes the extension):
DecimalIntegerLiteral :: 0 NonZeroDigit DecimalDigits(opt)
But ECMAScript 5 forbade doing that in strict-mode:
A conforming implementation, when processing strict mode code (see 10.1.1), must not extend the syntax of NumericLiteral to include OctalIntegerLiteral as described in B.1.1.
ECMAScript 6 (ECMAScript 2015) introduces BinaryIntegerLiteral and OctalIntegerLiteral, so now we have more coherent literals:
- BinaryIntegerLiteral, prefixed with 0b or 0B .
- OctalIntegerLiteral, prefixed with 0o or 0O .
- HexIntegerLiteral, prefixed with 0x or 0X .
The old OctalIntegerLiteral extension has been renamed to LegacyOctalIntegerLiteral, which is still allowed in non-strict mode.
Therefore, if you want to parse a number in base 8, use the 0o or 0O prefixes (not supported by old browsers), or use parseInt .
And if you want to be sure your numbers will be parsed in base 10, remove leading zeros, or use parseInt .
010- In strict mode (requires ECMAScript 5), it’s a syntax error.
- In non-strict mode, it may be a syntax error or return 8 (implementation dependent).
- Before ECMAScript 6, they’re syntax errors.
- In ECMAScript 6, they return 8 .
- It returns 8 .
- It returns 10 .
If you’re interested, you can find the current living specification here, and historical versions here.
Format numbers in javascript leading zero
Last updated: Jan 5, 2023
Reading time · 4 min# Add Leading Zeros to a Number in JavaScript
To add leading zeros to a number:
- Use the String() object to convert the number to a string.
- Call the padStart() method to add zeros to the start of the string.
- The padStart method will return a new string, padded with leading zeros.
Copied!function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > console.log(padWithLeadingZeros(3, 2)); // 👉️ "03" console.log(padWithLeadingZeros(3, 3)); // 👉️ "003" console.log(padWithLeadingZeros(3, 4)); // 👉️ "0003" console.log(padWithLeadingZeros(100, 2)); // 👉️ "100" // 👇️ Alternatively, simply use the Addition (+) operator const num = '00' + 3; console.log(num); // 👉️ "003"
The padWithLeadingZeros() function takes a number and its desired total length as parameters and pads the number with leading zeros if necessary.
The String.padStart method pads the current string with the provided string until the resulting string reaches the given length.
The padStart method takes the following 2 arguments:
Name Description targetLength The string gets padded with the pad string up to this length. padStart The string to pad the current string with. The targetLength argument also takes into consideration decimal characters or a minus sign.
An easy way to think about the method is that it pads the original string to a target length with a supplied string.
Copied!const num = 3; console.log(String(num).padStart(2, '0')); // 👉️ 03 console.log(String(num).padStart(3, '0')); // 👉️ 003 console.log(String(num).padStart(4, '0')); // 👉️ 0003
If you have a string of length 2 and you set the target length argument to 4 , the string will get padded with 2 leading zeros.
Copied!// 👇️ "0022" console.log(String(22).padStart(4, '0'));
Make sure to convert the number to a string before using the padStart() method.
If you always want to pad the number with a specific number of leading zeros, use the number’s length to determine the target length.
Copied!const num = 123; const str = String(num); // ✅ pad number with 2 leading zeros console.log(str.padStart(str.length + 2, '0')); // ✅ pad number with 3 leading zeros console.log(str.padStart(str.length + 3, '0'));
By adding n to the length of the number to determine the target length, we always add n leading zeros to the number.
If you convert the padded string back to a number, any of the leading zeros will automatically get dropped.
Copied!const num = 3; const result = Number(String(num).padStart(5, '0')); console.log(result); // 👉️ 3
If the length of the number exceeds the provided target length, the entire string gets returned from the padStart method.
Copied!function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > const num = 123456; console.log(padWithLeadingZeros(num, 3)); // 👉️ "123456"
# Padding negative numbers with leading zeros
If you need to handle negative numbers, you need to add an if statement that adds the minus sign after the leading zeros have been added.
Copied!function addLeadingZeros(num, totalLength) if (num 0) const withoutMinus = String(num).slice(1); return '-' + withoutMinus.padStart(totalLength, '0'); > return String(num).padStart(totalLength, '0'); > console.log(addLeadingZeros(3, 2)); // 👉️ "03" console.log(addLeadingZeros(-3, 3)); // 👉️ "-003"
We added an if statement to check if a negative number is provided to the function.
Note that we deliberately don’t include the minus sign in the target length for the new string.
To handle negative numbers, we just had to strip the minus, add the leading zeros and add the minus to the front of the string.
# Pad a number with leading zeros using the addition (+) operator
The addition (+) operator will convert the number to a string and will add the specified number of leading zeros to the beginning of the string.
Copied!const positive = '00' + 5; console.log(positive); // 👉️ "005" const negative = '-' + '00' + String(-5).slice(1); console.log(negative); // 👉️ "-005"
When using the addition operator with a number and a string, the number gets converted to a string and the two strings get concatenated.
We used the same approach to handle negative numbers as we did with the padStart method.
If you have to pad a number with leading zeros often, define a reusable function.
Copied!function padWithLeadingZeros(num, n) const char = '0'; return char.repeat(n) + num; > const num = 123; console.log(padWithLeadingZeros(num, 2)); // 👉️ 00123 console.log(padWithLeadingZeros(num, 3)); // 👉️ 000123 console.log(padWithLeadingZeros(num, 4)); // 👉️ 0000123
The padWithLeadingZeros function takes a number and how many leading zeros should be added to the number as parameters.
The function uses the String.repeat method to repeat the zero n times and adds it to the beginning of the string.
Copied!console.log('0'.repeat(3)); // 👉️ "000" console.log('0'.repeat(2)); // 👉️ "00"
You can also use a while loop to add leading zeros to a number.
# Pad a number with Leading Zeros using a while loop
This is a three-step process:
- Convert the number to a string.
- Use a while loop to iterate for as long as the string hasn’t reached the target length.
- Pad the string with leading zeros until it reaches the target length.
Copied!function padWithZero(num, targetLength) let str = String(num) while (str.length targetLength) str = '0' + str > return str > const num = 5; // ✅ pad with 2 leading zeros console.log(padWithZero(num, String(num).length + 2)); // 👉️ '005' // ✅ pad with 3 leading zeros console.log(padWithZero(num, String(num).length + 3)); // 👉️ '0005' // ✅ pad with 4 leading zeros console.log(padWithZero(num, String(num).length + 4)); // 👉️ '00005'
The padWithZero() function is very similar to the padStart method.
It takes a number and the desired target length as parameters and pads the number with leading zeros to the specified length.
The first step is to convert the number to a string.
The while loop iterates for as long as the string’s length is less than the desired target length.
On each iteration, we use the addition (+) operator to add a leading zero to the string.
Once the string reaches the desired target length, the condition in the while loop is no longer met.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to Output Numbers With Leading Zeros in JavaScript
Any number having 0’s before the non-zero digit or a string is known as a leading zero. For instance, 008, 05, 000XXX, and so on. Sometimes, developers must show errors during testing with leading zeros strings or numbers. JavaScript allows performing the mentioned operation using the addition (+) operator or the padStart() method.
This blog will describe the methods to get the numbers with leading zeros in JavaScript.
How to Output Numbers With Leading Zeros in JavaScript?
To get the numbers with leading zeros, use the given methods:
Method 1: Output Numbers With Leading Zeros Using Addition Operator
The addition operator “+” is used for concatenating numbers or strings. It can also be used to concatenate the number with leading zeros.
Syntax
Follow the provided syntax for using the addition operator:
Example
Create a variable “numLeadingZeros” and concatenate the number with zeros using the addition operator:
Print the concatenated number on the console:
As you can see the output displays a number with leading zeros:
Note: If you want to add leading zeros with the negative number then use the “slice()” method with the addition operator.
First, use the slice() method to cut the (-) sign from the string. Then, add the zeros to the number. After that, again add the (-) sign with the string using the (+) operator:
Print the number on the console:
The output indicates that the negative number is successfully concatenated with leading zeros:
Method 2: Output Numbers With Leading Zeros Using padStart() Method
To get the number with leading zeros, use the JavaScript “padStrat()” method. This method pads/joins the current string with another string (as often as necessary) until the resultant string is the specified length. The padding is added from the beginning of the given string.
Syntax
Use the below-given syntax for padding the strings using the padString() method:
- “targetLength” is the final length of the resultant string after padding.
- “padString” is the string that will pad with the given string.
Example
First, create a variable “numLeadingZeros” and store a number:
Then, call the “padStart()” method by passing the total length of the resultant string that is “3” and the padString “0” that will be padded with the given string “5”:
Output
We have provided all the essential information related to getting the number with leading zeros.
Conclusion
For adding and getting the number with leading zeros, use the addition operator (+) or the JavaScript “padStart()” method. For the negative numbers, use the “slice()” method with the addition operator (+). This blog describes the methods to get the numbers with leading zeros in JavaScript.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.