ave*_*ini 25 java double number-formatting
I use double values in my project and i would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when i print, for example, the value 2 it prints 2.0 .
public static double round(double d) {
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
Run Code Online (Sandbox Code Playgroud)
I want to print 2.00!
Is there a way to do this without using Strings?
Thanks!
EDIT: from your answers (wich I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this System.out.println("" + d) (where d is my double with value 2) it prints 2.00.
我开始认为没有办法做到这一点......对吗?无论如何,再次感谢您的回答,如果您知道解决方案,请告诉我们!
Pet*_*zki 50
你可以使用这样的东西:
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(d));
Run Code Online (Sandbox Code Playgroud)
编辑实际上回答了这个问题,因为我需要真正的答案,这出现在谷歌上,有人将其标记为答案,尽管当小数为0时这不会起作用.
dar*_*jan 19
使用java.text.NumberFormat这个:
NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
System.out.print(nf.format(decimalNumber));
Run Code Online (Sandbox Code Playgroud)
小智 8
你可以这样做:
double d = yourDoubleValue;
String formattedData = String.format("%.02f", d);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79152 次 |
| 最近记录: |