Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Frank Mckenna
To get the first 2 digits of a number convert the number to a string and call
the slice()
method to get the first 2 characters. Then convert the string back
to a number to get the first 2 digits.
const num = 1357; const first2Str = String(num).slice(0, 2); // 👉️ '13' const first2Num = Number(first2Str); // 👉️ 13
The first step is to use the String
object to convert the number to a string,
so we can call the
String.slice
method on it.
The first parameter we pass to the String.slice
method is the
start index
- the index at which we begin extraction of characters.
The second parameter is the end index
- extract characters up to this index,
but not including.
We start extracting characters at index 0
and go up to but not including index
2
.
0
and the last - str.length - 1
.end index
you provide to the String.slice
method is greater than the string's length, the method does not throw an error, instead it returns a copy of the entire string.const num = 1; const first2Str = String(num).slice(0, 2); // 👉️ '1' const first2Num = Number(first2Str); // 👉️ 1
The slice
method returns a string, so the last step is to convert it back to a
number and we have the first 2 digits of the number.