Get the last Four Digits of a Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 25, 2021

banner

Photo from Unsplash

Get the last Four Digits of a Number #

To get the last 4 digits of a number:

  1. Convert the number to a string and call the slice() method on the string, passing it -4 as a parameter.
  2. The slice method will return the last 4 character in the string.
  3. Convert the string back to a number to get the 4 last digits.
index.js
const num = 123456789; const last4Str = String(num).slice(-4); // 👉️ '6789' const last4Num = Number(last4Str); // 👉️ 6789

We first convert the number to a string, using the String object, 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 of characters.

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

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

index.js
const str = '12345678'; const last4 = str.slice(-4); // 👉️ '5678' const last4Again = str.slice(str.length - 4); // 👉️ '5678'

The slice method returns a string, so we need to convert it back to a number using the Number object. This gets us the last 4 digits from 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.