DecimalFormat(“ $ 0.00”)加零且不将小数放在应放置的位置

时间:2018-10-01 00:18:46

标签: java decimalformat

对于一堂课,我必须输入一些四分之一硬币,硬币和镍币,并将它们输出为美元。

如果我输入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)));
}

1 个答案:

答案 0 :(得分:1)

我知道以下代码很hacky,但是如果您不必使用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);