Java - 将小数点到2位小数

时间:2014-04-25 10:33:45

标签: java decimalformat

我想将变量retail_price四舍五入到小数点后两位。我试过几次,它总是给我一个错误。据我所知,有两种方法可以舍入到2位小数。对于这个例子,我真的只需要使用一次。导入它还是没有更好?帮助

        // The actionPerformed method executes when the user clicks the calculate button
    public void actionPerformed(ActionEvent e)
    {
        double retail_price;
        String input1;
        String input2;

        // Get the number from the users input in priceFeild1
        input1 = priceField1.getText();

        // Get the number from the users input in priceFeild2
        input2 = priceField2.getText();

        // Calculate out the priceFeilds to find the retail price.
        retail_price = Double.parseDouble(input1) + ((Double.parseDouble(input1) * (Double.parseDouble(input2) / 100)));

        // Show the results
        JOptionPane.showMessageDialog(null, "The whole sale cost of the item is: $" + input1 + ". "
                                                + "\nThe markup percentage of the item is: " +  input2 + "%." 
                                                + "\nIf those two numbers were correct, the retail price is: $" + retail_price);            
    }

4 个答案:

答案 0 :(得分:2)

您可以使用DecimalFormat来实现这一目标。首先将其初始化为:

final DecimalFormat df = new DecimalFormat("#.##");

而不是打印retail_price使用此:

df.format(retail_price)

请记住,如果您想要可靠的资金计算,则应使用BigDecimal而不是double。

答案 1 :(得分:1)

尝试

// Show the results
        JOptionPane.showMessageDialog(null, String.format("The whole sale cost of the item is: $%.2f. "
                                                + "\nThe markup percentage of the item is: %s%%." 
                                                + "\nIf those two numbers were correct, the retail price is: $%.2f", Double.parseDouble(input1), input2, retail_price));  

答案 2 :(得分:0)

这会做四舍五入..

retail_price = Math.round(retail_price * 100.0) / 100.0;

答案 3 :(得分:0)

这是我一行完成的操作。

double amount = Double.Parse(String.format("%.2f", 20.4425);

从根本上来说,这已经足够了。让我分解一下。

double amountIn = 20.4425;
String amountInString = String.format("%.2f", amountIn);
double amountOut = Double.parse(amountInString);

String.format()将双精度型转换为2进制的字符串,然后Parse将其转换为双精度型。简单高效且易于执行。