Get the Last 2 Digits of a Number in JavaScript


Borislav Hadzhiev

Sat Oct 23 20211 min read


Photo by Jack Sloop

Get the Last 2 Digits of a Number #

To get the last 2 digits of a number:

  1. Convert the number to a string and call the slice() method on the string, passing it -2 as a parameter.
  2. The slice method will return the last 2 character in the string.
  3. Convert the string back to a number to get the 2 last digits.
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 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 - 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 -2, means give me the last 2 characters of the string.

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

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

The slice method returns a string, so the last step is to convert it back to a number to get the last 2 digits of the number.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.