How to convert from Base36 to Base10 in JS

Viewed 2063

I have a base36 number 00001CGUMZYCB99J

But if I try convert it in JavaScript to base 10 with

parseInt("00001CGUMZYCB99J", 36);

I get wrong results like 177207000002463650 or 177207000002463648. The expected result is 177207000002463655. I found two websites that get the result right anyway: translatorscafe and dcode.

But how can I do this in JS?

2 Answers

The outcome of that conversion exceeds Number.MAX_SAFE_INTEGER (i.e. the base-10 value is too large to fit in a JavaScript integer), which means you need some sort of arbitrary precision library to do the conversion, for instance biginteger:

const BigInteger = require('biginteger').BigInteger;

let value = BigInteger.parse('00001CGUMZYCB99J', 36);

console.log( value.toString() ) // 177207000002463655

JavaScript stores all values in a double. Therefore, large numbers will have some of the less significant digits changed. If you want to deal with large numbers, you have to use a special library like this BigInteger one.

If you use this library, you can convert between bases like this:

BigInteger.parse("00001CGUMZYCB99J", 36);

Keep in mind that you need to keep using the library, you can't convert it back into a normal number, or you will face the same problem.

Related