将double转换为java中的两位小数

时间:2014-04-18 06:32:20

标签: java double decimalformat

我想将一个dobule转换为exaclty两个地方。我有相同查询的答案,但它们都不能满足我的问题。

这是我正在使用的代码:

Double d=15.99965754;
System.out.println("Value before formatting is : "+d);
String value=new DecimalFormat("##.00").format(d);
System.out.println("The value after formatting is :" +Double.parseDouble(value));

我得到的输出是

格式化前的值为:15.99965754 格式化后的值为:16.0

但我真正期待打印的是:

格式化前的值为:15.99965754 格式化后的值为:16.00

无论double值是多少,我都应该将小数精确到两个位置。

1 个答案:

答案 0 :(得分:7)

不解析值,只需打印

System.out.println("The value after formatting is :" + value);

另一种获得相同结果的方法

System.out.printf("The value after formatting is : %.2f", d);
相关问题