Sahithi Sahithi - 2 months ago 11
Javascript Question

Reverse digits of an integer in javascript

How do we reverse a number in javascript?

Answer

You could use an array for reversing a number with:

  • Save the sign
  • Get the absolute value
  • Convert it to string
  • Split the string
  • Reverse the array
  • Join the array
  • Convert to number
  • Apply the saved sign

var value = -123;
    sign = value < 0 ? -1 : 1,
    reversed = Math.abs(value).toString().split('').reverse().join('') * sign;

console.log(reversed);

Comments