How to get “shortest” BigDecimal that uniquely determines a given double

放肆的年华 提交于 2019-12-08 17:26:47

问题


Basically, I'm curious on how to get hold of new BigDecimal(Double.toString(d)) without going through the process of creating a string.

The documentation for Double.toString is quite complex (and interesting). As I understand it, the method does not actually return the string representation of the number actually represented by the given double, but the string representation of the (near by) shortest real number that uniquely identifies the given double.

(I don't actually need this. If I did, I'd probably go through a string anyway. I'm just curious about this algorithm that finds this "short" real number that uniquely determines the given double value.)

(This is a follow-up question on this question.)


回答1:


See: How to print floating-point numbers accurately and How to read floating point numbers accurately

implementations: here and here

There is a new publication on this subject that may be of interest to those looking at providing solutions. It (Grisu2) works without bignums if you are willing to settle for the shortest string in 99.8% of cases, and an accurate but not shortest string in the remaining cases.




回答2:


Perhaps you are thinking of BigDecimal.valueOf(double) which does this.



来源:https://stackoverflow.com/questions/6063704/how-to-get-shortest-bigdecimal-that-uniquely-determines-a-given-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!