Search code examples
javascriptradix

How to convert from Base36 to Base10 in JS


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?


Solution

  • 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