Search code examples
javascriptnode.jsgoogle-chrome-devtoolsradixbase36

Why JavaScript base-36 conversion appears to be ambiguous


I am currently writing a piece of JavaScript that uses base 36 encoding.

I came across this problem:

parseInt("welcomeback",36).toString(36)

Appears to return "welcomebacg".

I tested this in the Chrome developer's console and Node.js with the same result.

Is there any logical explanation for this result?


Solution

  • The result of parseInt("welcomeback",36) is larger than Number.MAX_SAFE_INTEGER (253-1) and thus cannot be accurately represented. A possible workaround is to perform base conversion with BigInt manually.

    const str = "welcomeback";
    const base = 36;
    const res = [...str].reduce((acc,curr)=>
       BigInt(parseInt(curr, base)) + BigInt(base) * acc, 0n);
    console.log(res.toString());
    console.log(res.toString(36));