Is there a better way to convert a Double to it's exact decimal String?

£可爱£侵袭症+ 提交于 2020-01-13 19:17:07

问题


I tried many ways to convert a Double to it's exact decimal String with String.format() and DecimalFormater and I found this so far :

String s = "-.0000000000000017763568394002505";
Double d = Double.parseDouble(s) * 100;
System.out.println((new java.text.DecimalFormat("###########################.################################################################################")).format(d));

(https://ideone.com/WG6zeC)

I'm not really a fan of my solution because it's ugly to me to make a huge pattern that does not covers all the cases.

Do you have another way to make this ?
I really want to have ALL the decimals, without scientific notation, without trailing zeros.

Thanks

P.S.: I need this without external libraries and in Java 1.7.


回答1:


Seems as if you have to deal with some precision. double is not intended for this use. Better use BigDecimal

String value="13.23000";
BigDecimal bigD=new BigDecimal(value);
System.out.println(bigD);
System.out.println(bigD.stripTrailingZeros().toPlainString());



回答2:


There is a big difference between new BigDecimal("0.1") and new BigDecimal(0.1). Using the String constructor can result in trailing zeros, and loses the effects of rounding to double on parsing the string. If the objective is to print the exact value of the double, you need to use BigDecimal's double constructor. Do any arithmetic in double, not BigDecimal.

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    String s = "-.0000000000000017763568394002505";
    double d = Double.parseDouble(s) * 100;
    System.out.println(new BigDecimal(d).toPlainString());
  }
}



回答3:


Try this code: You can also use toString() method, but it uses scientific notation. https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toPlainString()

BigDecimal bd = new BigDecimal("-.0000000000000017763568394002505");
System.out.println(bd.toPlainString());


来源:https://stackoverflow.com/questions/48804787/is-there-a-better-way-to-convert-a-double-to-its-exact-decimal-string

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