简体   繁体   English

处理金钱时尾随零

[英]Have trailing zero when dealing with money

I need to create a method that returns the total amount of money in dollar notation with two decimal places. 我需要创建一种方法,以小数点后两位返回美元表示的总金额。 Any help would be wonderful. 任何帮助都会很棒。 This is what I have so far... 这是我到目前为止所拥有的...

private final double QVALUE = 0.25;
private final double DVALUE = 0.10;
private final double NVALUE = 0.05;
private final double PVALUE = 0.01;

public double dollarValue() {
    double amount = (quarters * QVALUE) + (dimes * DVALUE) + 
        (nickels * NVALUE) + (pennies * PVALUE);
    return amount;
}

I have provided the values for each coin and the method I need to return a double in. Thanks! 我提供了每种硬币的值和返回双精度值所需的方法。谢谢!

Ex. 例如 When I get $1.50 for the total amount of money, it displays as $1.5, I need it to display $1.5 and I do not want to use DecimalFormat because it needs to return a String 当我获得总金额的1.50美元时,它显示为1.5美元,我需要它显示1.5美元,并且我不想使用DecimalFormat,因为它需要返回String

I don't understand what you mean by "it needs to return a String". 我不明白您的意思是“它需要返回一个字符串”。 Can't you just use String.format("%.2f", d); 您不能只使用String.format("%.2f", d); ?

May be this is what you want: 可能这就是您想要的:

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
String s = currencyFormat.format(1.5);

Result is "$1.50" 结果是"$1.50"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM