好的,如何将小数四舍五入到小数点后第二位,而不仅仅是小数点第一位?我必须创建一个菜单,“顾客”在其中点餐,我们必须包含小计、税费和小费。我的代码工作正常,除非总计是 3.8 美元,而实际应该是 3.80 美元。如何仅使用 Math.round() 来解决这个问题?我的菜单金钱部分的代码是
double SUBtotal = subTotal * 100.00;
System.out.println("Your current total is: $" +
Math.round(SUBtotal)/100.00);
System.out.println("Options:");
System.out.println(" 1. Order another item");
System.out.println(" 2. Checkout");
mainOp = scan.nextInt();
if (mainOp==2)
{
System.out.println(Order);
double tax = subTotal * 0.0825;
double taxSubtotal = tax + subTotal;
double please = taxSubtotal * 100.00;
double taxSubtotal2 = Math.round(please) / 100.00;
System.out.println("\nSubtotal (with tax): $ " + taxSubtotal2);
System.out.println("Tip: $");
double tip = scan.nextDouble();
double total = taxSubtotal + tip;
double total2 = total * 100.00;
double total3 = Math.round(total2) /100.00;
System.out.println("Final Total: $" + total3);
System.out.println();
System.out.println("Thank You For Ordering!");
}
非常感谢!
最佳答案
这是一个使用 DecimalFormat 来解决您的问题的小代码片段。
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(total3));
这会将您的十进制值打印为附加两位小数的字符串。 此外,您可以声明一个decimalFormat 变量,并在您的代码中任何地方(无论您想要显示小数点后两位值的任何位置)使用它。
谢谢
关于java - 小数点四舍五入到小数点后第二位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47448105/