Get the Last Digit of a Number in JavaScript


Borislav Hadzhiev

Last updated: Aug 28, 2022


Photo from Unsplash

Get the Last Digit of a Number #

To get the last digit of a number:

  1. Convert the number to a string and call the slice() method on the string, passing it -1 as a parameter.
  2. The slice method will return the last character in the string.
  3. Convert the string back to a number to get the last digit.
// 👇️ Decimal numbers const num1 = 1357.579; const lastDigit1Str = String(num1).slice(-1); // 👉️ '9' const lastDigit1Num = Number(lastDigit1Str); // 9 // 👇️ Integers const num2 = 1357; const lastDigit2Str = String(num2).slice(-1); // 👉️ '7' const lastDigit2Num = Number(lastDigit2Str); // 👉️ 7

This approach works for integer and float numbers.

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.

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

The only parameter we passed to the slice method is the start index - the index at which to start extraction.

Passing a negative index of -1 means - give me the last character of the string.

This is the same as passing string.length - 1 as the start index.

const str = 'Hello World'; const last1 = str.slice(-1); // 👉️ d console.log(last1); const last1Again = str.slice(str.length - 1); // 👉️ d console.log(last1Again);

The slice method returns a string, so 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.