Get the Last 2 Digits of a Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

Get the Last 2 Digits of a Number #

To get the last 2 digits of a number:

  1. Convert the number to a string.
  2. Call the slice() method on the string, passing it -2 as a parameter.
  3. The slice method will return the last 2 characters in the string.
  4. Convert the string back to a number to get the 2 last digits.
index.js
const num = 2468; const last2Str = String(num).slice(-2); // 👉️ '68' const last2Num = Number(last2Str); // 👉️ 68

The first step is to use the String object to convert the number to a string, so we can use the String.slice method.

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

The only argument we passed to the slice method is the start index - the index of the first character to be included in the new string.

Passing a negative index of -2 means give me the last 2 characters of the string.

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

index.js
const str = 'Hello World'; const last2 = str.slice(-2); console.log(last2); // 👉️ ld const last2Again = str.slice(str.length - 2); console.log(last2Again); // 👉️ ld

The slice method returns a string, so the last step is to convert the string back to a number to get the last 2 digits of the 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.