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.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看