Get the last Four Digits of a Number in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20211 min read

banner

Photo by Mael Balland

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 #

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