2015-10-22 22 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