Reverse a number in JavaScript
In this tutorial, you are given a number. Write a JavaScript program to reverse the number.
Solution
To reverse a given number, convert the given number to string, split the string into an array of characters, reverse the array, join the array elements to a string, and then convert the reversed string back to number using parseFloat(). We may preserve the sign of the given number by using Math.sign().
Program
Given number is IN num
. We reverse the number using string operations.
function reverseNumber(num) {
//convert to string an reverse it
reversed = num.toString()
.split('')
.reverse()
.join('')
//convert back to number
reversed = parseFloat(reversed);
//preserve the sign of given number
reversed *= Math.sign(num);
return reversed;
}
let num = 153;
let result = reverseNumber(num);
console.log(result);