Java中的美元货币格式

Tid*_*tis 25 java string currency

在Java中,我如何有效地将浮点数1234.56和类似的BigDecimals转换为类似的字符串$1,234.56

我正在寻找以下内容:

String 12345.67变为String$12,345.67

我也期待与要做到这一点Float,并BigDecimal为好.

Bri*_*per 33

有一个适合语言环境的习语很好用:

import java.text.NumberFormat;

// Get a currency formatter for the current locale.
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(120.00));
Run Code Online (Sandbox Code Playgroud)

如果您当前的区域设置位于美国,println则将打印$ 120.00

另一个例子:

import java.text.NumberFormat;
import java.util.Locale;

Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(120.00));
Run Code Online (Sandbox Code Playgroud)

这将打印:£120.00


kro*_*ock 8

DecimalFormat moneyFormat = new DecimalFormat("$0.00");
System.out.println(moneyFormat.format(1234.56));
Run Code Online (Sandbox Code Playgroud)