Convert double to String in Java [duplicate]

大城市里の小女人 提交于 2020-01-05 12:30:40

问题


I am to convert a double value to a String.

double d=12345678.999;
String str = String.valueOf(d);

or, just plain

String str = ""+d;

Does it, however in the exponent form-- returning the String value:

1.2345678999E7

I need the value as is in the String:

12345678.999

Is there a way to do this? I can parse the string for the value of exponent-- the portion after 'E' and go from there, but there must be an easier way of doing this.

//===========================

EDIT:

the length of the decimal part in the input isn't known, it can be any number of digits:

12345678.999

or

12345678.9999999

Imposing a format for the decimal part would fix the number of decimal digits(?)


回答1:


You should use NumberFormat to format Strings so that they do not show up in scientific notation.

String str = NumberFormat.getInstance().format(d);



回答2:


use String.format():

double d=12345678.999;
System.out.println(String.format("%12.3f", d));


来源:https://stackoverflow.com/questions/25067808/convert-double-to-string-in-java

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