可能重复:
将小数点后的双精度数加到2位有效数字
我试图用前导零来格式化一个双精度到2位小数,并且没有运气.这是我的代码:
Double price = 32.0;
DecimalFormat decim = new DecimalFormat("#.##");
Double price2 = Double.parseDouble(decim.format(price));
Run Code Online (Sandbox Code Playgroud)
我希望输出32.00相反,我得到32.0
任何解决方案?
Ton*_*nis 54
OP需要领先的零.如果是这样,那么根据Tofubeer:
DecimalFormat decim = new DecimalFormat("0.00");
Run Code Online (Sandbox Code Playgroud)
编辑:
请记住,我们在谈论格式化数字,而不是数字的内部表示.
Double price = 32.0;
DecimalFormat decim = new DecimalFormat("0.00");
Double price2 = Double.parseDouble(decim.format(price));
System.out.println(price2);
Run Code Online (Sandbox Code Playgroud)
将price2使用默认格式打印.如果要打印格式化的表示,请使用以下格式打印:
String s = decim.format(price);
System.out.println("s is '"+s+"'");
Run Code Online (Sandbox Code Playgroud)
从这个角度parseDouble()来看,我不认为你做的是你想要的,也不是.
Tof*_*eer 14
试试这个:
DecimalFormat decim = new DecimalFormat("#.00");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74635 次 |
| 最近记录: |