Java 中的美元货币格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3075743/
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
USD Currency Formatting in Java
提问by Tidbtis
In Java, how can I efficiently convert floats like 1234.56
and similar BigDecimals into Strings like $1,234.56
在 Java 中,如何有效地将1234.56
类似 BigDecimals 的浮点数转换为类似的字符串$1,234.56
I'm looking for the following:
我正在寻找以下内容:
String 12345.67
becomes String $12,345.67
字符串12345.67
变成字符串$12,345.67
I'm also looking to do this with Float
and BigDecimal
as well.
我也想用Float
和来做这件事BigDecimal
。
回答by krock
DecimalFormat moneyFormat = new DecimalFormat("import java.text.NumberFormat;
// Get a currency formatter for the current locale.
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(120.00));
.00");
System.out.println(moneyFormat.format(1234.56));
回答by Brian Clapper
There's a locale-sensitive idiom that works well:
有一个对语言环境敏感的习语很有效:
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));
If your current locale is in the US, the println
will print $120.00
如果您当前的语言环境在美国,println
则将打印 $120.00
Another example:
另一个例子:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
public class test {
public static void main(String[] args) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
String pattern = "$#,##0.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
BigDecimal bigDecimal = new BigDecimal("12345.67");
String bigDecimalConvertedValue = decimalFormat.format(bigDecimal);
String convertedValue = decimalFormat.format(12345.67);
System.out.println(bigDecimalConvertedValue);
System.out.println(convertedValue);
}
}
This will print: £120.00
这将打印:£120.00
回答by ABHISHEK HONEY
Here is the code according to your input and output::
这是根据您的输入和输出的代码:
The output of the program is $12,345.67 for both BigDecimal and number and it works for float also.
BigDecimal 和 number 程序的输出为 12,345.67 美元,它也适用于浮点数。
##代码##