我是 Java 的新手,我最近编写了一个代码来计算您需要多少零钱才能购买一件定价为 x 的商品。它运作良好;我唯一的问题是,只要没有任何零钱在百分之一的地方(例如: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 来解决它,现在效果很好。
最佳答案
你可以这样调用:
String.format("%.2f", i);
所以在你的情况下:
...
System.out.print("Change Owed: $");
System.out.println((String.format("%.2f", z)/100));
...
String.format()
在您想将其四舍五入到某些有效数字时很有用。在这种情况下,“f”代表 float 。
关于java - 我不确定如何在我的 Java 代码中正确地舍入它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33283244/