A number can be formatted to prepend a 0 to single-digit numbers using 3 approaches:
Method 1: Using padStart() method
The padStart() method is used to pad a string with another string to a certain length. The padding is started from the left of the string. It takes two parameters, the target length, and the string to be replaced with. The number to be formatted is first converted to a string by passing it to the String constructor. The padStart() method is used on this string with the length parameter given as 2 and the string to be replaced with, given the character ‘0’. This will format any single-digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is.
Syntax:
prepended_number = String(number).padStart(2, '0')
Example:
Javascript
function prependNumber() { let single_digit = 1; let two_digits = 03; let prepended_out = String(single_digit).padStart(2, '0' ); let prepended_out2 = String(two_digits).padStart(2, '0' ); console.log(prepended_out); console.log(prepended_out2); } prependNumber(); |
01 03
Method 2: Checking if number is less than 9
In this method, the number is first checked if it is less than 9. If true, the character ‘0’ is appended to the number otherwise, the number is returned without any change. This will format any single digit number to 2 digits by prepending a ‘0’ and leave 2 digit numbers as is.
Syntax:
function prependZero(number) { if (number < 9) return "0" + number; else return number; }
Example:
Javascript
function prependZero(number) { if (number < 9) return "0" + number; else return number; } function prependNumber() { let single_digit = 1; let two_digits = 03; let prepended_out = prependZero(single_digit); let prepended_out2 = prependZero(two_digits); console.log(prepended_out); console.log(prepended_out2); } prependNumber(); |
01 03
Method 3: Using the slice() method
The slice() method is used to extract parts of a string from the specified starting and ending indices. First, the number is prepended with a ‘0’ character regardless of it being a single digit. This will make the single digit number into 2 digits but the 2-digit number would be converted to a 3-digit one with the extra ‘0’. The slice() method is used to extract the last 2 digits of the resulting number. This will correctly get the last 2 digits of the 2-digit number discarding the extra ‘0’ added to it. The single-digit number is now formatted with a ‘0’.
Syntax:
prepended_number = ("0" + number).slice(-2)
Example:
Javascript
function prependNumber() { let single_digit = 1; let two_digits = 03; let prepended_out = ( "0" + single_digit).slice(-2); let prepended_out2 = ( "0" + two_digits).slice(-2); console.log(prepended_out); console.log(prepended_out2); } prependNumber(); |
01 03