2015-10-22 23 views
4

我對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去解決它,現在它工作得很好。

回答

2

您可以撥打這樣的事情來圓你的號碼:

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

所以你的情況:

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

String.format()只要您想將其四捨五入到某些有意義的數字,就很有用。在這種情況下,「f」代表浮動。

2

此行爲是預期的。你不希望數字攜帶尾隨零。 您可以使用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)); 

輸出:貨幣符號

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

輸出:

4.70 
5.68 

您也可以你的貨幣符號添加到DecimalFormat

$4.70 
$5.68 

編輯:

你甚至可以告訴DecimalFormat如何通過設置RoundingMode通過df.setRoundingMode(RoundingMode.UP);

1

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

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

%.2f將圓任何浮動(「F」代表浮動)截止到小數點後2位,由「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... 

您可能需要做一些閱讀到String.format()如果您正在使用Java開始了。這是一個非常強大和有用的方法。

從我的理解:

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); 
} 

所有最適合您未來的項目!

+1

我想看看爲什麼'String.format()'方法是他的「最佳選擇」的一些解釋。這聽起來像你傳播個人喜好。 – showp1984