我對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