Search code examples
javascriptnumbersradix

Javascript Number.toString(radix) behavior


Why (73).toString(36) returns 21 and (0.73).toString(36) returns 0.qa2voha2volfpsnhmyhqia4i and not 0.21?


Solution

  • That's because floats are stored as binary fractions (a number divided by a power of 2), and 73/100 cannot be expressed as a non-repeating fraction in binary. Thus internally, it's storing a value close to 0.73 but not exactly equal. That's why you get so many digits in the toString() method.

    73/100 also can't be expressed as a non-repeating fraction in base 36. In general, for a fraction a/b you can only get a fixed number of digits after the decimal point in a given base x if you can reduce a/b to the form c/(x^n) for some integers c and n.