# Reverse numbers without string cast in Javascript

Stepped onto an article at The Code Project on how to reverse a number in javascript without casting it to a string and decided to understand how this works by my self.

## The solution

On way of doing it, when it is forbidden to cast to a `string`

it to apply the
`modulus`

operator and multiplying by `10`

.

As the author explains it:

This little function has a simple loop that executes until the incoming parameter (number) becomes zero. Notice the symmetry between "number" and "reversed", inside the loop. The value of "reversed" (result) starts out at zero and keeps getting multiplied by 10 and then increased by the number mod 10. The "number" (incoming value) keeps getting decreased by the number mod 10 and then is divided by 10.

var reverse = function(number) { var reversed = 0 while (number > 0) { reversed *= 10 reversed += number % 10 number -= number % 10 number /= 10 } return reversed }

It's pretty simple once you get it.

If I were to implement a reverse number function where string casting is allowed, I would do something like this:

var reverse2 = function(number) { return ('' + number).split('').reverse().join('') }

The `reverse`

function is actually much slower, but it is doing the reverse in
the right way.

## Example

If I try to reverse a large number, casting to a string will not produce a number and therefore render it useless in further calculations.

console.time('start') console.log(reverse(123456789098871234567890988712345678909887)) console.timeEnd('start') //The reversed number output. 6.622246482288666e+41 start: 6.602ms console.time('start2') console.log(reverse2(123456789098871234567890988712345678909887)) console.timeEnd('start2') //The reversed string output 14+e3217889098765432.1 start2: 0.773ms

As you can see my problem, when reversing a cast number to string, is that
large numbers are shortened and added the `e+X`

notation. This part is now
reversed to the starting point of my reversed string. Whereas reversing
a number with math changes the order and creates a new shortened number
notation when I `console.log`

the reversed number.

## Conclusion

If, and that's a **BIG** if, your numbers are small and you need to reverse
them, cast them to a string as it's much faster than doing the math on them,
but are you dealing with larges number and they need to be reversed for some
reason, you need to stick to the math otherwise you'll never succeed.