Java 货币数字格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2379221/
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-13 06:45:19  来源:igfitidea点击:

Java Currency Number format

javacurrencynumber-formatting

提问by DD.

Is there a way to format a decimal as following:

有没有办法格式化小数如下:

100   -> "100"  
100.1 -> "100.10"

If it is a round number, omit the decimal part. Otherwise format with two decimal places.

如果是整数,则省略小数部分。否则格式为两位小数。

采纳答案by extraneon

I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.

我对此表示怀疑。问题是,如果 100 是浮点数,则它永远不会是 100,它通常是 99.9999999999 或 100.0000001 或类似的东西。

If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.

如果您确实想以这种方式对其进行格式化,则必须定义一个 epsilon,即与整数的最大距离,如果差异较小,则使用整数格式,否则使用浮点数。

Something like this would do the trick:

像这样的事情可以解决问题:

public String formatDecimal(float number) {
  float epsilon = 0.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}

回答by dj_segfault

Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"

是的。您可以使用java.util.formatter。您可以使用像“%10.2f”这样的格式字符串

回答by Stefan De Boey

you should do something like this:

你应该做这样的事情:

public static void main(String[] args) {
    double d1 = 100d;
    double d2 = 100.1d;
    print(d1);
    print(d2);
}

private static void print(double d) {
    String s = null;
    if (Math.round(d) != d) {
        s = String.format("%.2f", d);
    } else {
        s = String.format("%.0f", d);
    }
    System.out.println(s);
}

which prints:

打印:

100

100

100,10

100,10

回答by duffymo

I'd recommend using the java.text package:

我建议使用 java.text 包:

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

This has the added benefit of being locale specific.

这具有特定于语言环境的额外好处。

But, if you must, truncate the String you get back if it's a whole dollar:

但是,如果必须,截断返回的字符串,如果它是一整美元:

if (moneyString.endsWith(".00")) {
    int centsIndex = moneyString.lastIndexOf(".00");
    if (centsIndex != -1) {
        moneyString = moneyString.substring(1, centsIndex);
    }
}

回答by wu liang

I did not find any good solution after google search, just post my solution for other to reference. use priceToStringto format money.

谷歌搜索后我没有找到任何好的解决方案,只是发布我的解决方案供其他人参考。使用priceToString格式化货币。

public static String priceWithDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.00");
    return formatter.format(price);
}

public static String priceWithoutDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.##");
    return formatter.format(price);
}

public static String priceToString(Double price) {
    String toShow = priceWithoutDecimal(price);
    if (toShow.indexOf(".") > 0) {
        return priceWithDecimal(price);
    } else {
        return priceWithoutDecimal(price);
    }
}

回答by Adrian Adamczyk

If you want work on currencies, you have to use BigDecimal class. The problem is, there's no way to store some float numbers in memory (eg. you can store 5.3456, but not 5.3455), which can effects in bad calculations.

如果您想处理货币,则必须使用 BigDecimal 类。问题是,无法在内存中存储一​​些浮点数(例如,您可以存储 5.3456,但不能存储 5.3455),这会影响错误的计算。

There's an nice article how to cooperate with BigDecimal and currencies:

有一篇关于如何与 BigDecimal 和货币合作的好文章:

http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html

http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html

回答by Viktor Nordling

This is what I did, using an integer to represent the amount as cents instead:

这就是我所做的,使用整数将金额表示为美分:

public static String format(int moneyInCents) {
    String format;
    Number value;
    if (moneyInCents % 100 == 0) {
        format = "%d";
        value = moneyInCents / 100;
    } else {
        format = "%.2f";
        value = moneyInCents / 100.0;
    }
    return String.format(Locale.US, format, value);
}

The problem with NumberFormat.getCurrencyInstance()is that sometimes you really want $20 to be $20, it just looks better than $20.00.

问题NumberFormat.getCurrencyInstance()在于,有时您真的希望 20 美元变成 20 美元,它只是看起来比 20.00 美元好。

If anyone finds a better way of doing this, using NumberFormat, I'm all ears.

如果有人找到了更好的方法来做到这一点,使用 NumberFormat,我会全力以赴。

回答by Dirk Lachowski

I'm using this one (using StringUtils from commons-lang):

我正在使用这个(使用来自 commons-lang 的 StringUtils):

Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");

You must only take care of the locale and the corresponding String to chop.

您必须只关心要切割的语言环境和相应的字符串。

回答by Lukas

Format from 1000000.2 to 1 000 000,20

格式从 1000000.2 到 1 000 000,20

private static final DecimalFormat DF = new DecimalFormat();

public static String toCurrency(Double d) {
    if (d == null || "".equals(d) || "NaN".equals(d)) {
        return " - ";
    }
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
    DecimalFormatSymbols symbols = DF.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    String ret = DF.format(bd) + "";
    if (ret.indexOf(",") == -1) {
        ret += ",00";
    }
    if (ret.split(",")[1].length() != 2) {
        ret += "0";
    }
    return ret;
}

回答by Aezur

I know this is an old question but...

我知道这是一个老问题,但是......

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}