102

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

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

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

4

22 回答 22

172

我建议使用 java.text 包:

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

这具有特定于区域设置的额外好处。

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

if (moneyString.endsWith(".00")) {
    int centsIndex = moneyString.lastIndexOf(".00");
    if (centsIndex != -1) {
        moneyString = moneyString.substring(1, centsIndex);
    }
}
于 2010-03-04T13:07:43.953 回答
141
double amount =200.0;
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(currencyFormatter.format(amount));

或者

double amount =200.0;
System.out.println(NumberFormat.getCurrencyInstance(new Locale("en", "US"))
        .format(amount));

显示货币的最佳方式

输出

$200.00

如果您不想使用符号,请使用此方法

double amount = 200;
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println(twoPlaces.format(amount));

200.00

这也可以使用(带千位分隔符)

double amount = 2000000;    
System.out.println(String.format("%,.2f", amount));          

2,000,000.00

于 2014-08-20T19:20:12.517 回答
49

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

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

像这样的东西可以解决问题:

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
  }
}
于 2010-03-04T12:51:00.833 回答
19

谷歌搜索后我没有找到任何好的解决方案,只是发布我的解决方案供其他人参考。使用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);
    }
}
于 2012-10-13T17:07:39.583 回答
7
NumberFormat currency = NumberFormat.getCurrencyInstance();
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

输出:

$123.50

如果您想更改货币,

NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CHINA);
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

输出:

¥123.50
于 2020-02-21T23:52:43.207 回答
6

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

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

您只需要注意语言环境和相应的字符串即可切碎。

于 2012-12-07T13:29:34.767 回答
6

这是最好的方法。

    public static String formatCurrency(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

100 -> “100.00”
100.1 -> “100.10”

于 2017-10-17T09:15:58.980 回答
5

你应该这样做:

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);
}

打印:

100

100,10

于 2010-03-04T12:49:26.203 回答
5

我认为这对于打印货币来说很简单明了:

DecimalFormat df = new DecimalFormat("$###,###.##"); // or pattern "###,###.##$"
System.out.println(df.format(12345.678));

产出:12,345.68 美元

以及该问题的一种可能解决方案:

public static void twoDecimalsOrOmit(double d) {
    System.out.println(new DecimalFormat(d%1 == 0 ? "###.##" : "###.00").format(d));
}

twoDecimalsOrOmit((double) 100);
twoDecimalsOrOmit(100.1);

输出:

100

100.10

于 2015-04-25T05:31:15.780 回答
5

我们通常需要做相反的事情,如果你的 json money 字段是一个浮点数,它可能是 3.1 、 3.15 或只是 3。

在这种情况下,您可能需要对其进行四舍五入以正确显示(并且稍后能够在输入字段上使用掩码):

floatvalue = 200.0; // it may be 200, 200.3 or 200.37, BigDecimal will take care
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);

BigDecimal valueAsBD = BigDecimal.valueOf(value);
    valueAsBD.setScale(2, BigDecimal.ROUND_HALF_UP); // add digits to match .00 pattern

System.out.println(currencyFormatter.format(amount));
于 2015-12-16T18:43:10.183 回答
4

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

于 2010-03-04T12:43:14.547 回答
4

你可以做这样的事情并传递整数,然后传递美分。

String.format("$%,d.%02d",wholeNum,change);
于 2013-08-23T01:23:04.670 回答
4

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

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));
    }
}
于 2013-06-24T15:16:22.147 回答
4

我同意@duffymo 的观点,即您需要使用这些java.text.NumberFormat方法来处理这类事情。您实际上可以在其中本地进行所有格式设置,而无需自己进行任何 String 比较:

private String formatPrice(final double priceAsDouble) 
{
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    if (Math.round(priceAsDouble * 100) % 100 == 0) {
        formatter.setMaximumFractionDigits(0);
    }
    return formatter.format(priceAsDouble);
}

需要指出的几点:

  • 整体Math.round(priceAsDouble * 100) % 100只是在解决双打/浮点数的不准确性。基本上只是检查我们是否四舍五入到数百位(也许这是美国的偏见)是否还有剩余的美分。
  • 去除小数的诀窍是setMaximumFractionDigits()方法

无论您确定小数是否应该被截断的逻辑,setMaximumFractionDigits()都应该被使用。

于 2014-10-15T05:06:47.837 回答
3

格式从 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;
}
于 2013-04-18T09:57:44.393 回答
2

这篇文章真的帮助我最终得到了我想要的。所以我只是想在这里贡献我的代码来帮助别人。这是我的代码和一些解释。

以下代码:

double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));

将返回:

€ 5,-
€ 5,50

实际的 jeroensFormat() 方法:

public String jeroensFormat(double money)//Wants to receive value of type double
{
        NumberFormat dutchFormat = NumberFormat.getCurrencyInstance();
        money = money;
        String twoDecimals = dutchFormat.format(money); //Format to string
        if(tweeDecimalen.matches(".*[.]...[,]00$")){
            String zeroDecimals = twoDecimals.substring(0, twoDecimals.length() -3);
                return zeroDecimals;
        }
        if(twoDecimals.endsWith(",00")){
            String zeroDecimals = String.format("€ %.0f,-", money);
            return zeroDecimals; //Return with ,00 replaced to ,-
        }
        else{ //If endsWith != ,00 the actual twoDecimals string can be returned
            return twoDecimals;
        }
}

调用方法 jeroensFormat() 的方法 displayJeroensFormat

    public void displayJeroensFormat()//@parameter double:
    {
        System.out.println(jeroensFormat(10.5)); //Example for two decimals
        System.out.println(jeroensFormat(10.95)); //Example for two decimals
        System.out.println(jeroensFormat(10.00)); //Example for zero decimals
        System.out.println(jeroensFormat(100.000)); //Example for zero decimals
    }

将有以下输出:

€ 10,50
€ 10,95
€ 10,-
€ 100.000 (In Holland numbers bigger than € 999,- and wit no decimals don't have ,-)

此代码使用您当前的货币。就我而言,那是荷兰,所以我的格式化字符串与美国的人不同。

  • 荷兰:999.999,99
  • 美国:999,999.99

只需注意这些数字的最后 3 个字符。我的代码有一个 if 语句来检查最后 3 个字符是否等于“,00”。要在美国使用它,您可能必须将其更改为“.00”,如果它还不起作用的话。

于 2013-11-30T02:07:04.720 回答
2

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

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

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

于 2012-10-13T17:22:08.680 回答
2

对于想要格式化货币但不希望它基于本地的人,我们可以这样做:

val numberFormat = NumberFormat.getCurrencyInstance() // Default local currency
val currency = Currency.getInstance("USD")            // This make the format not locale specific 
numberFormat.setCurrency(currency)

...use the formator as you want...
于 2019-07-02T15:05:03.410 回答
2

我很疯狂地编写了自己的函数:

这会将整数转换为货币格式(也可以修改为小数):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }
于 2018-04-15T04:36:25.127 回答
1

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

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);
}

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

如果有人找到更好的方法,使用 NumberFormat,我会全力以赴。

于 2012-12-07T03:00:28.533 回答
1
  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }
于 2018-11-01T13:34:48.193 回答
0
double amount = 200.0;

NumberFormat Us = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(Us.format(amount));

输出
$200.00

于 2021-07-24T18:44:47.480 回答