JavaScript Code

How to reverse a number?


Problem Statement

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 num. we reverse the number

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);