【问题标题】:DecimalFormat ("$0.00") adding zeros and not putting decimal where it should goDecimalFormat ("$0.00") 添加零而不是将小数放在应该去的地方
【发布时间】:2018-10-01 00:18:46
【问题描述】:

对于一个班级,我必须输入一些硬币、一角硬币和五分硬币,然后将它们输出为美元。

如果我输入4 硬币、10 硬币和5 镍币,我得到的是$225.00,而不是$2.25

有人可以帮帮我吗?

public static void main(String[] args) {

    System.out.print("Enter Number of Quaters: ");
    Scanner quarter = new Scanner (System.in);
    int quarters = quarter.nextInt();

    System.out.print("Enter Number of Dimes: ");
    Scanner dime = new Scanner (System.in);
    int dimes = dime.nextInt();

    System.out.print("Enter Number of Nickels: ");
    Scanner nickel = new Scanner (System.in);
    int nickels = nickel.nextInt();

    DecimalFormat df = new DecimalFormat("$0.00");
    System.out.print("The total is ");
    System.out.println(df.format((quarters * 25) + (dimes * 10) + (nickels * 5)));
}

【问题讨论】:

  • 我没有检查,但我确定十进制格式需要小数,而不是 int。转换为double,然后格式化。
  • 您必须将 ((Quarts * 25) + (dimes * 10) + (nickels * 5)) 除以 100。您将所有内容都转换为美分并期望美元。
  • 也看看这个答案,列表中的第四个答案使用货币格式:stackoverflow.com/questions/2379221/java-currency-number-format(回复@AshraffAliWahab 答案,你必须除以100.0,而不是100,这仍然会给你是int。)
  • 你学会如何使用.printf了吗?将 %.2d 与 / 100.0 结合使用可能是您的教授正在寻找的。​​span>

标签: java decimalformat


【解决方案1】:

我知道下面的代码很老套,但如果你不必使用DecimalFormat,那么这应该格式化一个int 值,正确地代表美分到美元:

int total = (quarters * 25) + (dimes * 10) + (nickels * 5);
String strTotal = (total<10 ? "0" + String.valueOf(total) : String.valueOf(total));
String formattedTotal = "$" + (strTotal.length()<3 ? "0" : strTotal.substring(0, strTotal.length()-2))
                            + "." + strTotal.substring(strTotal.length()-2, strTotal.length());

System.out.println(formattedTotal);

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多