Get the first Digit of a Number in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20211 min read

banner

Photo by Åaker

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

We 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 #

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