Java 使用前导 0 将双精度格式设置为 2 个小数位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3973763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format double to 2 decimal places with leading 0s
提问by Bat_Programmer
Possible Duplicate:
Round a double to 2 significant figures after decimal point
可能的重复:将双精度舍入
到小数点后的 2 个有效数字
I am trying to format a double to 2 decimal places with leading zeros and there's no luck. Here is my code:
我试图用前导零格式化双到 2 个小数位,但没有运气。这是我的代码:
Double price = 32.0;
DecimalFormat decim = new DecimalFormat("#.##");
Double price2 = Double.parseDouble(decim.format(price));
And I want output to be 32.00
instead I get 32.0
Any solutions??
我想要输出32.00
而不是我得到32.0
任何解决方案?
采纳答案by Tony Ennis
OP wants leading zeroes. If that's the case, then as per Tofubeer:
OP 需要前导零。如果是这种情况,那么根据 Tofubeer:
DecimalFormat decim = new DecimalFormat("0.00");
Edit:
编辑:
Remember, we're talking about formatting numbers here, not the internal representation of the numbers.
请记住,我们在这里讨论的是格式化数字,而不是数字的内部表示。
Double price = 32.0;
DecimalFormat decim = new DecimalFormat("0.00");
Double price2 = Double.parseDouble(decim.format(price));
System.out.println(price2);
will print price2
using the defaultformat. If you want to print the formatted representation, print using the format:
将price2
使用默认格式打印。如果要打印格式化的表示,请使用以下格式打印:
String s = decim.format(price);
System.out.println("s is '"+s+"'");
In this light, I don't think your parseDouble()
is doing what you want, nor can it.
从这个角度parseDouble()
来看,我不认为你正在做你想做的,也不能。
回答by TofuBeer
Try this:
尝试这个:
DecimalFormat decim = new DecimalFormat("#.00");