How to use the slice() method In GIT
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: In this example we are using slice() method.
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();
Output
01 03
How to format numbers by prepending 0 to single-digit numbers ?
We will be having a number and we need to check whether the given number has prepending 0 or not. If a number does not acquire prepending 0 then we will add that 0 with the help of some methods. If 0 is present then we will print that number the same as it is.
A number can be formatted to prepend a 0 to single-digit numbers using 3 approaches:
Table of Content
- Method 1: Using padStart() method
- Method 2: Checking if number is less than 9
- Method 3: Using the slice() method
- Method 4: Using Intl.NumberFormat object