Possible Duplicate:
Is there an equivalent for toPrecision() in Java?
我创建了一个方法,该方法假设将数字限制为小数点后两位,但它的作用是将数字显示为小数点后两位,然后显示零。
此外,从下面的数字计算中我可以注意到它错误地舍入了数字。数字应该是 478.03 129.06 348.97
.
这里出了什么问题?
PS。我只是遵循伪代码,我无法导入超过import java.io.*;
的任何内容
我的输出:
Employee's Last Name: dfsdfsdf
Employment Status (F or P): p
Hourly Pay Rate: 8.35
Hours Worked: 51.5
-------------------------------------------------------
Name Status Gross Taxes Net
dfsdfsdf Part Time 478.040000 129.070000 348.970000
我的代码,我输入所有数据,然后尝试输出它:
private static void outputData(String name, char status, double pay)
{
if (status == "p".charAt(0))
{
System.out.println("-------------------------------------------------------");
System.out.println("Name\tStatus\t\tGross\tTaxes\tNet");
System.out.printf("%s\tPart Time\t\t%f\t%f\t%f\n\n",
name,
roundDouble(pay),
roundDouble(calculateTaxes(pay)),
roundDouble(pay - calculateTaxes(pay)));
}
else if (status == "f".charAt(0))
{
System.out.println("-------------------------------------------------------");
}
}
更多代码,这是应该进行转换的方法:
private static double roundDouble(double number)
{
return Double.parseDouble(String.format("%.2f", number));
}
最佳答案
您可以尝试使用 NumberFormat
来代替
double value = 478.03123456789;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(value));
输出478.03
ps - 它也可能有助于获得原始值;)
关于java - 我将 double 转换为小数点后两位的方法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12525534/