gofloating-pointradixbase36

How do I convert a Float64 to Base36 in Go?


I have say the value 0.36388617850285954, when I use the Javascript .toString(36) function I get the output "0.d3lh1pogpwk". I would like to replicate this in golang however I have no real starting point.

How would I carry this out?


Solution

  • Go base36 packages don't convert this properly because Javascript's toString(36) does not base36 encode the the float64, it represents it using a radix of 36. The documentation is lackluster as to the specifics of how this function works on Number objects (and only number objects), and the logic is really bizarre as well, but is located here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString#Description

    Basically, in the case of a non whole number, the value is converted to a number in baseN (where N is the radix passed in), by concatenating the conversion of the left side of the decimal with a dot, then with the conversion of the right side of the decimal. e.g.

    baseNLeft + "." + baseNRight

    There also other considerations explained in the documentation link above about negatives. Specifically that they preserve the negative and simply convert the digits then replace the negative sign instead of using the two's complement representation.

    In my opinion, this functionality is not suitable for any other language than Javascript itself, and I would advise caution in using it cross-language.

    As to the answering of the question itself as to how you would do this in Go. Follow the same goofy semantics and unit test it against hundreds of thousands of test cases to check that f(x) = y in both Javascript and your Go implementation. The actual specification of the logic is in the ECMA specification here: https://www.ecma-international.org/ecma-262/6.0/#sec-tostring-applied-to-the-number-type

    Note: There is a Javascript engine implemented in Go called otto (github.com/robertkrimen/otto), but it does not properly perform the Number.toString(radix) functionality. Plus it is a heavy library to import if this would be it's only purpose anyway.