gpt4 book ai didi

java - DecimalFormat ("$0.00")添加零并且没有将小数放在它应该去的地方

转载 作者:行者123 更新时间:2023-11-30 05:59:04 25 4
gpt4 key购买 nike

对于一门课,我必须输入一些 25 美分、10 美分和 5 美分的硬币,并将它们输出为美元。

如果我输入 4 25 美分、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)));
}

最佳答案

我知道下面的代码非常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);

关于java - DecimalFormat ("$0.00")添加零并且没有将小数放在它应该去的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52583223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com