如何正确显示最多两位小数(美分)的价格,包括 Java 中的尾随零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1734282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:01:53  来源:igfitidea点击:

How to properly display a price up to two decimals (cents) including trailing zeros in Java?

javadoubleroundingdecimal-point

提问by denchr

There is a good question on rounding decimals in Java here. But I was wondering how can I include the trailing zeros to display prices in my program like: $1.50, $1.00

有在Java的舍入小数一个很好的问题在这里。但我想知道如何在我的程序中包含尾随零以显示价格,例如:$1.50, $1.00

The simple solution of

简单的解决方法

String.format("%.2g%n", 0.912385);

works just fine, but omits the trailing zero if it is at the last decimal place. The issue comes up in my program even though I only use expressions like this:

工作正常,但如果它在最后一个小数位,则省略尾随零。即使我只使用这样的表达式,问题也出现在我的程序中:

double price = 1.50;

When I do calculations with different prices (add, multiply, etc.) the result is primarily displayed like this:

当我用不同的价格(加、乘等)进行计算时,结果主要显示如下:

.5000000000000003

So, using the String.format works fine for this purpose, but it truncates the above example to

因此,为此目的使用 String.format 效果很好,但它会将上面的示例截断为

.5

Is there a proper way to show the trailing zero at the second decimal place? Or both zeros if the output of a calculation should be

有没有正确的方法在小数点后第二位显示尾随零?或者如果计算的输出应该是两个零

.00

采纳答案by duffymo

I would recommend that you do this:

我建议你这样做:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
double price = 2.50000000000003;
System.out.println(currencyFormatter.format(price));

This has the virtue of be locale-specific as well. This will work, for example, if you're in the euro zone instead of the US.

这也具有特定于区域设置的优点。例如,如果您在欧元区而不是美国,这将起作用。

回答by Bart Kiers

It can probably be done with String.format(...), but you could use DecimalFormat:

它可能可以用 String.format(...) 来完成,但你可以使用DecimalFormat

double price = 2.50000000000003;
DecimalFormat formatter = new DecimalFormat("
String s = String.format("$%.2f", 2.50);
.00"); System.out.println(formatter.format(price)); // print: .50

回答by dustmachine

Have you tried:

你有没有尝试过:

public static String getFormattedData(String actualString) 
    {
        String subString = "0.0";

        if(actualString.contains("."))
        {   
            subString = actualString.substring(actualString.indexOf("."), actualString.trim().length()); 

            if(Double.parseDouble(subString) > 0.0)
                return actualString;
            else
                actualString = actualString.substring(0, actualString.indexOf("."));
        }
        return actualString;
    }

That will do the trick.

这样就行了。

回答by Pascal Thivent

While others answers are perfectly valid (especially duffymo's one), you have a much bigger problem than formatting the display. You are actually using a totally wrongtype for a money amount which is a discretevalue. Instead of a double, you should really consider using a java.lang.BigDecimal.

虽然其他答案完全有效(尤其是 duffymo 的答案),但您遇到的问题比格式化显示要大得多。对于离散值的金额,您实际上使用了完全错误的类型。而不是 a ,您应该真正考虑使用 a 。doublejava.lang.BigDecimal

(EDIT: ... or a well implemented Money class as duffymo pointed out in a comment, for example classes from JScience's monetarymodule or the more recent Joda-Money- which has still to be released as an official version.)

(编辑:...或者像 duffymo 在评论中指出的那样实现良好的 Money 类,例如来自 JScience 的货币模块的类或最近的Joda-Money- 仍需作为正式版本发布。)

回答by Shiva

##代码##