我对Java相当陌生,而且我最近编写了一个代码,用于计算您需要支付多少金额项目。它运作良好;我唯一的问题是,只要没有百分之一的亏损(例如4.60美元),它就会下降到十分之一(4.6美元)。我不确定如何在Java代码中正确舍入这个数据
如果有人知道如何解决这个问题,我将非常感激。我有下面的代码。
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()'方法是他的“最佳选择”的一些解释。这听起来像你传播个人喜好。 – showp1984