Converting Numbers to Strings
- Convert both numbers to strings using the
toString()
method. - Get the last character (digit) of each string using the
slice()
method. - Compare the last digits using the ===.
- Return
true
if the last digits are the same, otherwise returnfalse
.
Syntax:
string.slice(startIndex, endIndex);
Example:
// Define function to check if two numbers have the same last digit
function haveSameLastDigit(num1, num2) {
// Getting last digit using "toString" and "slice" methods
const lastDigit1 = num1.toString().slice(-1);
const lastDigit2 = num2.toString().slice(-1);
// Return if last digits are same or not
return lastDigit1 === lastDigit2;
}
// Define two numbers
const number1 = 123;
const number2 = 453;
// Calling function with arguments
const result = haveSameLastDigit(number1, number2);
// Output the result
console.log(result);
Output
true
JavaScript Program to Check if Two Numbers have Same Last Digit
In this article, we will discuss how to check if two numbers have the same last digit in JavaScript. Checking the last digit of a number is a common requirement in programming tasks, and it can be useful in various scenarios. We will explore an approach using JavaScript to accomplish this task.