Get the First 2 Digits of a Number in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Frank Mckenna

Get the First 2 Digits of a Number #

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.

index.js
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.

Indexes are zero-based in JavaScript. The index of the first character in a string is 0 and the last - str.length - 1.
Even if the 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.
index.js
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee