In JavaScript, you can get the last digit of an integer in the following ways:
Using Remainder Operator
You can use the remainder operator (%) to get the last digit of an integer in the following way:
// ES6+ const lastDigit = (num) => num % 10; console.log(lastDigit(0)); // 0 console.log(lastDigit(1234)); // 4 console.log(lastDigit(-1234)); // -4
In the example above, the remainder operator (%) works by dividing a given number by 10 and returning the remainder. It uses truncated division, and is equivalent to the following:
// ES6+
function lastDigit(num) {
const quotient = Math.trunc(num / 10);
return (num - (10 * quotient));
}
console.log(lastDigit(0)); // 0
console.log(lastDigit(1234)); // 4
console.log(lastDigit(-1234)); // -4
This works in the following way:
// num = 1234 // lastDigit = 1234 - (10 * Math.trunc(1234 / 10)) // lastDigit = 1234 - (10 * Math.trunc(123.4)) // lastDigit = 1234 - (10 * 123) // lastDigit = 1234 - 1230 // lastDigit = 4
Converting to String and Retrieving Last Character
You could do the following:
- Convert the integer to a string;
- Get the last character of the string;
- Convert the string back to integer;
- Add negative sign to the last digit if integer was negative.
// ES13+
function lastDigit(num) {
const numStr = num.toString();
const lastChar = numStr.at(-1);
const lastDigitUnsigned = Number.parseInt(lastChar, 10);
return (num < 0) ? -lastDigitUnsigned : lastDigitUnsigned;
}
console.log(lastDigit(0)); // 0
console.log(lastDigit(1234)); // 4
console.log(lastDigit(-1234)); // -4
To support versions prior to ES13, you can use numStr[numStr.length - 1] instead of numStr.at(-1).
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.