java - 我将 double 转换为小数点后两位的方法无法正常工作

标签 java double decimal conventions decimal-point

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/

相关文章:

java - double用二进制科学计数法不能准确表示,Java如何精确显示?

mysql - 在mySQL中格式化十进制?

c# - MVC3 十进制字段未正确验证

java - 关于扫描仪、文件编写器和 getClass().getResource() 的混淆

java - Java PriorityQueue poll()值的顺序

c++ - C++ 中的 int 和 double 运算

c# - 小数点后保留一位,不四舍五入

c# - 如何在 .net 中将 int 转换为 decimal

java - 只有一个部署在 Tomcat 中运行缓慢,另一个运行正常/快速

java - 读取文件内容并写入控制台