如何格式化给定语言环境的双精度值和小数位数? [英] How to format double value for a given locale and number of decimal places?
问题描述
如何使用 NumberFormat
格式化给定区域设置<的
double
值/ code>(默认语言环境已足够)和给定的小数位数?
How can I use NumberFormat
to format a double
value for a given Locale
(default locale is sufficient) and for a given number of decimal places?
例如,我有以下值:
double d1 = 123456.78;
double d2 = 567890;
我想以下列方式打印它们,例如使用美国语言环境和2位小数:
And I want to print them in the following way, for example with US locale and 2 decimal places:
123,456.78
567,890.00
在这种情况下,我实际上并不关心舍入模式,因为这些双值是从具有给定比例的 BigDecimal
获得的,所以它们的小数位数总是小于或等于我想要打印的小数位数。
I don't actually care about rounding mode in this case, because these double values are gained from a BigDecimal
with the given scale, so their number of decimal places is always lesser or equal than the number of decimal places I want to print.
编辑:
为了使事情更加明确,问题在于我想以依赖于语言环境的方式显示货币,但是具有固定的小数位数。上面的示例显示了如果系统区域设置为 en_US
,应如何格式化值。现在假设,系统区域设置是 cs_CZ
(捷克语),因此应该以这种方式格式化相同的数字:
To make things a bit more clear, the thing is that I want to display money in a locale dependent way, but with a fixed number of decimal places. The example above showed, how the values should be formatted if the system locale is en_US
. Now lets say, the system locale is cs_CZ
(Czech), so the same numbers should be formatted in this way:
123 456,78
567 890,00
现在,如何设置NumberFormat以始终显示2个小数位,但是根据当前区域设置显示千位分隔符和小数点?
Now, how can I set up a NumberFormat to always display 2 decimal places, but to display thousands separator and decimal point based on the current locale?
推荐答案
如果您想阅读NumberFormat的文档,解决方案将是显而易见的:
If you care to read NumberFormat's documentation, the solution would be obvious:
double d1 = 123456.78;
double d2 = 567890;
// self commenting issue, the code is easier to understand
Locale fmtLocale = Locale.getDefault(Category.FORMAT);
NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println(formatter.format(d1));
System.out.println(formatter.format(d2));
System.out.println(fmtLocale.toLanguageTag());
在我的机器上打印出来:
On my machine this prints out:
123 456,78
567 890,00
pl-PL
123 456,78
567 890,00
pl-PL
我相信这就是你要找的东西,你不必弄乱模式。我不这样做 - 例如,有一些区域设置将数字分组,而不是三组(这就是我们讨论分组分隔符和不 的原因)千位分隔符)。
I believe this is what you are looking for, and you don't have to mess-up with patterns. I wouldn't do that - for instance there are locales which group digits by two, not by three (this is the reason we talk about grouping separator and not thousands separator).
这篇关于如何格式化给定语言环境的双精度值和小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!