Get the second Digit of a Number in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20211 min read

banner

Photo by Itay Peer

Get the second Digit of a Number #

To get the second digit of a number:

  1. Convert the number to a string.
  2. Access the string at index 1, using square brackets notation e.g. String(num)[1].
  3. Convert the result back to a number to get the second digit of the number.
index.js
const num = 98765; const secondDigitStr = String(num)[1]; console.log(secondDigitStr); // ๐Ÿ‘‰๏ธ 8 console.log(typeof secondDigitStr); // ๐Ÿ‘‰๏ธ string const secondDigitNum = Number(secondDigitStr); console.log(secondDigitNum); // ๐Ÿ‘‰๏ธ 1 console.log(typeof secondDigitNum); // ๐Ÿ‘‰๏ธ number

To be able to get the second 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 1 returns the second 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