doulingzou1712 2018-09-26 18:15 采纳率: 0%
浏览 92
已采纳

如何在Go中将Float64转换为Base36?

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?

  • 写回答

1条回答 默认 最新

  • dongsicheng5262 2018-09-26 18:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?