EN
JavaScript - check if number is palindrome
9
points
In this short article, we would like to show how to check if a number is a palindrome using JavaScript.
Definition:
Palindromes are characters sequence that we can read the same backward as forward (e.g.
121,12321).
The solution shown in the article allows you to check if the integer and floating-point numbers are palindromes.
Practical example:
// ONLINE-RUNNER:browser;
const isPalindrome = (number) => {
const string = number.toString();
for (let i = 0, j = string.length - 1; i < j; ++i, --j) {
if (string[i] !== string[j]) {
return false;
}
}
return true;
};
// Usage example:
console.log(isPalindrome(12321)); // true
console.log(isPalindrome(12.21)); // true
console.log(isPalindrome(454)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(3.14)); // false