我不确定如何在我的 Java 代码中正确地舍入它

I'm not sure how to round this properly in my Java code

我是 Java 的新手,我最近编写了一个代码来计算您需要多少零钱才能购买一件标价为 y 的商品。它运作良好;我唯一的问题是,只要没有任何零钱在百分之一的地方(例如:4.60 美元),它就会向下舍入到十分之一的地方(4.6 美元)。

如果有人知道如何解决这个问题,我将不胜感激。我在下面发布了代码。

class Main {
    public static void main(String[] args) throws IOException {

      Scanner scan = new Scanner(System.in);

      double x;
      double y;
      double z;

      System.out.print("Enter the price of the product: $");
      x = scan.nextDouble();
      System.out.print("Enter what you payed with: $");
      y = scan.nextDouble();
      z = (int)Math.round(100*(y-x));

      System.out.print("Change Owed: $");
      System.out.println((z)/100);

      int q = (int)(z/25);
      int d = (int)((z%25/10));
      int n = (int)((z%25%10/5));
      int p = (int)(z%25%10%5);

      System.out.println("Quarters: " + q);
      System.out.println("Dimes: " + d);
      System.out.println("Nickels: " + n);
      System.out.println("Pennies: " + p);

    }
}

编辑:感谢所有回答我问题的人!我最终使用 DecimalFormat 来解决它,现在效果很好。

此行为是预期的。您不希望数字带有尾随零。 您可以使用 DecimalFormat 将它们表示为带有尾随零的 String,四舍五入为两位数。

示例:

DecimalFormat df = new DecimalFormat("#0.00");
double d = 4.7d;
System.out.println(df.format(d));

d = 5.678d;
System.out.println(df.format(d));

输出:

4.70
5.68

您还可以将您的货币符号添加到 DecimalFormat:

DecimalFormat df = new DecimalFormat("$#0.00");

带货币符号的输出:

.70
.68

编辑:

您甚至可以告诉 DecimalFormat 如何通过设置 RoundingModedf.setRoundingMode(RoundingMode.UP);

来四舍五入您的数字

你可以这样调用:

String.format("%.2f", i);

所以在你的情况下:

...
System.out.print("Change Owed: $");
System.out.println((String.format("%.2f", z)/100));
...

String.format() 在您想将其四舍五入到某些有效数字时很有用。在这种情况下 "f" 代表浮动。

String.format()方法是我个人的喜好。例如:

float z;
System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));

%.2f 会将任何浮点数('f' 代表浮点数)四舍五入到小数点后两位,通过更改 'f' 之前的数字,您可以更改四舍五入到的小数点数。例如:

//3 decimal points
System.out.println(String.format("Change Owed: $%.3f", (float) ((z) / 100)));

//4 decimal points
System.out.println(String.format("Change Owed: $%.4f", (float) ((z) / 100)));

// and so forth...

如果您从 Java 开始,您可能需要阅读 String.format()。这是一个非常强大和有用的方法。

据我了解:

public static void main(String[] args) throws IOException {

    Scanner scan = new Scanner(System.in);

    double x;
    double y;
    double z;

    System.out.print("Enter the price of the product: $");
    x = scan.nextDouble();
    System.out.print("Enter what you payed with: $");
    y = scan.nextDouble();
    z = (int) Math.round(100 * (y - x));

    System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));

    int q = (int) (z / 25);
    int d = (int) ((z % 25 / 10));
    int n = (int) ((z % 25 % 10 / 5));
    int p = (int) (z % 25 % 10 % 5);

    System.out.println("Quarters: " + q);
    System.out.println("Dimes: " + d);
    System.out.println("Nickels: " + n);
    System.out.println("Pennies: " + p);
}

祝你未来的项目一切顺利!