我已经搜索了互联网,但找不到任何解决方案(也许,我搜索很差)。我想将String
"108595000.5"
转换为double
,并且使用了以下方法:
Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");
[不幸的是,他们两个都返回1.08595E8
。我怎样才能毫无问题地将此String
转换为double
?
您使用的方法不返回1.08595E8
,而是返回该数字,而您抱怨的是控制台中该数字的表示形式(或作为String
)。
但是,您可以指定如何以指定的格式输出double
自己,请参见以下示例:
public static void main(String[] args) {
String value = "108595000.5";
// use a BigDecimal to parse the value
BigDecimal bd = new BigDecimal(value);
// choose your desired output:
// either the String representation of a double (undesired)
System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
// or an engineering String
System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
// or a plain String (might look equal to the engineering String)
System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
// or you specify an amount of decimals plus a rounding mode yourself
System.out.println("rounded with fix decimal places:\t"
+ bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
double: 1.085950005E8
engineering: 108595000.5
plain: 108595000.5
rounded with fix decimal places: 108595000.50
尝试使用
value = new BidDecimal(yourString);
doubleValue = value.doubleValue();
如果需要exact值。
如果要在","
之后输入2个数字,则>]
double a = yourDouble;
System.out.printf("%.2f",a)