gpt4 book ai didi

Java——四舍五入到小数点后两位

转载 作者:行者123 更新时间:2023-12-01 23:01:55 24 4
gpt4 key购买 nike

我想将变量retail_price四舍五入到小数点后两位。我已经尝试了几次,但它总是给我一个错误。据我所知,有两种方法可以四舍五入到小数点后两位。对于这个例子,我实际上只需要使用它一次。导入还是不导入会更好?帮助

        // 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);
}

最佳答案

您可以使用 DecimalFormat 来实现这一点。首先像这样初始化它:

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

而不是打印 Retail_price 使用此:

df.format(retail_price)

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

关于Java——四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com