Get the first Digit of a Number in JavaScript


Borislav Hadzhiev

Last updated: Aug 29, 2022


Photo from Unsplash

Get the first Digit of a Number #

To get the first digit of a number:

  1. Convert the number to a string.
  2. Access the string at index 0, using square brackets notation e.g. String(num)[0].
  3. Convert the result back to a number to get the first digit of the number.
const num = 123456; const firstDigitStr = String(num)[0]; console.log(firstDigitStr); // 👉️ 1 console.log(typeof firstDigitStr); // 👉️ string const firstDigitNum = Number(firstDigitStr); console.log(firstDigitNum); // 👉️ 1 console.log(typeof firstDigitNum); // 👉️ number

To be able to get the first digit of a number, we converted it to a string using the String object.

You can access the characters of a string, by using bracket notation and specifying an index.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0 and the last - str.length - 1.

Accessing the character at index 0 returns the first digit in the number, however, it is still of type string.

The last step is to use the Number object to convert it back to a number.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.