Get the First and Last Digits of a Number in JavaScript

Last updated: Mar 3, 2024
8 min

#Get the First Digit of a Number in JavaScript

To get the first digit of a number:

1. Convert the number to a string.
2. Access the string at index `0`, using square brackets notation e.g. `String(num)[0]`.
3. Convert the result back to a number to get the first digit of the number.
index.js
```Copied!```const num = 123456;

// โ get first digit of number as string
const firstDigitStr = String(num)[0];
console.log(firstDigitStr); // ๐๏ธ 1
console.log(typeof firstDigitStr); // ๐๏ธ string

// โ get first digit of number as integer
const firstDigitNum = Number(firstDigitStr);
console.log(firstDigitNum); // ๐๏ธ 1
console.log(typeof firstDigitNum); // ๐๏ธ number
``````

The code sample above returns the first digit of a number.

If you need to get the last digit, use the following code sample instead.

index.js
```Copied!```// ๐๏ธ 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

// ----------------------------------------------

// ๐๏ธ using modulo % operator (without conversion)
const num = 123456;

const lastDigit = num % 10;
console.log(lastDigit); // ๐๏ธ 6
``````

We used the String() constructor to convert the number to a string.

You can use bracket notation to access a character in a string by index.

index.js
```Copied!```const num = 1234567;

console.log(String(num)[0]); // ๐๏ธ 1
``````
JavaScript indexes are zero-based, so the index of the first character in a string is `0` and the index of the last character is `str.length - 1`.

Accessing the character at index `0` returns the first digit in the number, however, it is still of type string.

The last step is to use the `Number` object to convert it back to a number.

index.js
```Copied!```const num = 1234567;

const result = Number(String(num)[0]);
console.log(result); // ๐๏ธ 1

console.log(typeof result); // ๐๏ธ number
``````

If you have to do this often, define a reusable function.

index.js
```Copied!```function getFirstDigit(num) {
return Number(String(num)[0]);
}

console.log(getFirstDigit(123456)); // ๐๏ธ 1
console.log(getFirstDigit(9877)); // ๐๏ธ 9
console.log(getFirstDigit(45678)); // ๐๏ธ 4
console.log(getFirstDigit(0)); // ๐๏ธ 0
``````

The `getFirstDigit` function takes a number as a parameter and returns the first digit of the supplied number.

The same approach can be used to get the first N digits of a number.

index.js
```Copied!```function getFirstNDigits(number, n) {
return Number(String(number).slice(0, n));
}

const num = 123456789;

// ๐๏ธ get the first 2 digits of a number
console.log(getFirstNDigits(num, 2)); // ๐๏ธ 12

// ๐๏ธ get the first 3 digits of a number
console.log(getFirstNDigits(num, 3)); // ๐๏ธ 123

// ๐๏ธ get the first 4 digits of a number
console.log(getFirstNDigits(num, 4)); // ๐๏ธ 12345
``````

The `getFirstNDigits` function takes a number and N as parameters and returns the first N digits of the number.

#Get the Last Digit of a Number in JavaScript

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.
index.js
```Copied!```// ๐๏ธ 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

// ----------------------------------------------

// ๐๏ธ using modulo % operator (without conversion)
const num = 123456;

const lastDigit = num % 10;
console.log(lastDigit); // ๐๏ธ 6
``````

This approach works for integers and floating-point 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.

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

The only argument 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".

The `String.slice()` method can be passed negative indexes to count backward.

index.js
```Copied!```const str = 'bobbyhadz.com';

console.log(str.slice(-1)); // ๐๏ธ m

console.log(str.slice(-2)); // ๐๏ธ om

console.log(str.slice(-3)); // ๐๏ธ com
``````

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

index.js
```Copied!```const str = 'bobbyhadz.com';

const last1 = str.slice(-1);
console.log(last1); // ๐๏ธ m

const last1Again = str.slice(str.length - 1);
console.log(last1Again); // ๐๏ธ m
``````

The `slice` method returns a string, so the last step is to use the `Number()` constructor to convert it back to a number.

index.js
```Copied!```const num = 1357;

const lastDigitStr = String(num).slice(-1); // ๐๏ธ "7"

const lastDigitNum = Number(lastDigitStr);
console.log(lastDigitNum); // ๐๏ธ 7
console.log(typeof lastDigitNum); // ๐๏ธ number
``````

The same approach can be used to get the last N digits of a number.

index.js
```Copied!```const num2 = 1357;
const lastDigit2Str = String(num2).slice(-3);
const lastDigit2Num = Number(lastDigit2Str);

console.log(lastDigit2Num); // ๐๏ธ 357
``````

We passed a negative index of `-3` to the `slice` method to get the last 3 digits of the number.

If you have to do this often, define a reusable function.

index.js
```Copied!```function getLastDigit(num) {
return Number(String(num).slice(-1));
}

console.log(getLastDigit(123456)); // ๐๏ธ 6
console.log(getLastDigit(12345)); // ๐๏ธ 5
console.log(getLastDigit(1234)); // ๐๏ธ 4
console.log(getLastDigit(123)); // ๐๏ธ 3
``````

The `getLastDigit` function takes a number as a parameter and returns the last digit of the number.

The same approach can be used to get the last N digits of a number.

index.js
```Copied!```function getLastNdigits(number, n) {
return Number(String(number).slice(-n));
}

const num = 123456789;

// ๐๏ธ get the last 2 digits of a number
console.log(getLastNdigits(num, 2)); // ๐๏ธ 89

// ๐๏ธ get the last 3 digits of a number
console.log(getLastNdigits(num, 3)); // ๐๏ธ 789

// ๐๏ธ get the last 4 digits of a number
console.log(getLastNdigits(num, 4)); // ๐๏ธ 6789
``````

#Get the first Digit of a Number using a `while` loop

You can also use a `while` loop to get the first digit of a number.

This is a three-step process:

1. Use a `while` loop to iterate for as long as the number is greater than or equal to `10`.
2. Divide the number by `10` to remove the last digit.
3. Reassign the result to the variable.
index.js
```Copied!```function getFirstDigit(num) {
let first = num;

while (first >= 10) {
first = first / 10;
}

return Math.floor(first);
}

console.log(getFirstDigit(123456)); // ๐๏ธ 1
console.log(getFirstDigit(9877)); // ๐๏ธ 9
console.log(getFirstDigit(45678)); // ๐๏ธ 4
console.log(getFirstDigit(0)); // ๐๏ธ 0
``````

The `while` loop iterates for as long as the number is greater than or equal to `10`.

On each iteration, we divide the number by `10` to remove the last digit.

index.js
```Copied!```const num = 123456;

console.log(Math.floor(num / 10)); // ๐๏ธ 12345

console.log(Math.floor(num / 10 / 10)); // ๐๏ธ 1234
``````

The last step is to use the Math.floor() function to round the result down to the nearest integer.

index.js
```Copied!```console.log(Math.floor(5.99)); // ๐๏ธ 5
console.log(Math.floor(5.01)); // ๐๏ธ 5
``````

Once the number is not greater than or equal to `10` (we have a single digit), we exit the `while` loop and return the first digit.

You can slightly tweak the function if you need to get the first N digits of a number.

index.js
```Copied!```function getFirst2Digits(num) {
let first2 = num;

while (first2 >= 100) {
first2 = first2 / 10;
}

return Math.floor(first2);
}

console.log(getFirst2Digits(123456)); // ๐๏ธ 12
console.log(getFirst2Digits(9877)); // ๐๏ธ 98
console.log(getFirst2Digits(45678)); // ๐๏ธ 45
console.log(getFirst2Digits(0)); // ๐๏ธ 0
``````

The function takes a number and returns the first 2 digits of the number.

On each iteration, we check if the `first2` variable stores a value greater than or equal to `100` and divide it by `10`.

#Get the last digit of a number using modulo `%` operator

You can also use the modulo `%` operator to get the last digit of a number.

The modulo operator will return the last digit of the number by calculating the remainder of dividing the number by `10`.

index.js
```Copied!```function getLastDigit(num) {
return num % 10;
}

console.log(getLastDigit(123456)); // ๐๏ธ 6
console.log(getLastDigit(12345)); // ๐๏ธ 5
console.log(getLastDigit(1234)); // ๐๏ธ 4
console.log(getLastDigit(123)); // ๐๏ธ 3
``````

The modulo (%) operator returns the remainder dividing one number by another.

index.js
```Copied!```console.log(123 % 10); // ๐๏ธ 3
console.log(12 % 10); // ๐๏ธ 2
console.log(1 % 10); // ๐๏ธ 1
``````

A single digit is always going to be less than `10`, so we calculate the remainder of dividing the number by `10` to get the last digit of the number.

The same approach can be used to get the last N digits of a number.

index.js
```Copied!```const num = 123456789;

const last = num % 10;
console.log(last); // ๐๏ธ 9

// โ get last 2 digits of number
const last2 = num % 100;
console.log(last2); // ๐๏ธ 89

// โ get last 3 digits of number
const last3 = num % 1000;
console.log(last3); // ๐๏ธ 789

// โ get last 4 digits of number
const last4 = num % 10000;
console.log(last4); // ๐๏ธ 6789
``````

For example, to get the last 2 digits of a number, we get the remainder of dividing the number by `100` because two digits are guaranteed to be less than `100`.

If you need to get the last `4` digits of a number, you have to divide than `10000` because 4 digits are guaranteed to be less than `10000`.

You can also use the `Array.pop()` method to get the last digit of a number.

The `String.match()` method can be used to get the first N digits of a number.

#Get the first N digits of a Number using `match()`

You can also use the `String.match()` method to get the first N digits of a number.

index.js
```Copied!```const number = 123456789;

const match = String(number).match(/[0-9]{2}/)[0];

console.log(match); // ๐๏ธ 12
``````

The String.match method matches a string against a regular expression.

index.js
```Copied!```const number = 123456789;

// ๐๏ธ [ '12', index: 0, input: '123456789', groups: undefined ]
console.log(String(number).match(/[0-9]{2}/));
``````

The method returns an array containing the matches (if any) or `null` if no matches are found.

The argument we passed to the method is a regular expression.

The forward slashes `/ /` mark the beginning and end of the regular expression.

The square brackets `[]` are called a character class and match the digits in the range `0` to `9`.

The curly braces `{}` are used to match exactly N occurrences of the preceding item (the digits).

You have to update the value between the square brackets depending on how many digits you want to get from the number.

index.js
```Copied!```const number = 123456789;

const match = String(number).match(/[0-9]{3}/)[0];

console.log(match); // ๐๏ธ 123
``````

The code sample returns the first 3 digits of the number.

The `String.match` method returns a string. If you need to convert the result to a number, use the `Number()` constructor.

index.js
```Copied!```const number = 123456789;

const match = String(number).match(/[0-9]{3}/)[0];

console.log(match); // ๐๏ธ "123"

const result = Number(match);
console.log(result); // ๐๏ธ 123
``````

If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

#Get the last digit of a number using `Array.pop()`

You can also use the `Array.pop()` method to get the last digit of a number.

This is a three-step process:

1. Convert the number to a string.
2. Split the string into an array of digits.
3. Use the `Array.pop()` method to get the last digit.
index.js
```Copied!```function getLastDigit(num) {
return Number(String(num).split('').pop());
}

console.log(getLastDigit(123456)); // ๐๏ธ 6
console.log(getLastDigit(12345)); // ๐๏ธ 5
console.log(getLastDigit(1234)); // ๐๏ธ 4
console.log(getLastDigit(123)); // ๐๏ธ 3
``````

We used the `String()` constructor to convert the number to a string to be able to call the `split()` method.

index.js
```Copied!```const num = 123456;

// ๐๏ธ [ '1', '2', '3', '4', '5', '6' ]
console.log(String(num).split(''));
``````

When supplied with an empty string, the `split()` method splits the string on each character.

We used the `Array.pop()` method to remove and return the last element from the array.

index.js
```Copied!```const num = 123456;

// ๐๏ธ [ '1', '2', '3', '4', '5', '6' ]
console.log(String(num).split(''));

// ๐๏ธ "6"
console.log(String(num).split('').pop());
``````

The last step is to use the `Number` class to convert the string to a number.