我正在制作披萨计算器,但我的结果是“7.5美元”,而不是“7.50美元”。我有这个十进制格式代码用我下面的代码写出来,但它似乎不起作用。有什么想法吗?
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double diameter;
double labourCost = 1.00;
diameter = Double.parseDouble(diameterInput.getText());
double storeCost = 1.50;
double materialsCost = 0.50 * diameter;
double totalCost = labourCost + storeCost + materialsCost;
DecimalFormat x = newDecimalFormat("0.00");
costOutput.setText("The cost of the pizza is $" + totalCost);
答案 0 :(得分:2)
您没有使用任何操作的结果(“x”)。我猜测在最后一行用“x”替换“totalCost”会有帮助吗?
答案 1 :(得分:0)
您需要使用十进制格式化器将浮点值转换为字符串。
// Make a new formatter with your format
DecimalFormat myFormatter = new DecimalFormat("$##.00");
// Convert your number to a human readable string
String output = myFormatter.format(22.99999f);
System.out.println(output); // Prints $23.00
有关各种模式https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
的详细信息,请参阅此页面