使用逗号和两位小数的方式格式化Java中的BigDecimal数字

14

我希望能够使用逗号和2位小数格式化BigDecimal数字。

例如:

Amount is: 5.0001 and formatted to: 5.00
Amount is: 999999999.999999 and formatted to: 999,999,999.99
Amount is: 1000.4999 and formatted to: 1,000.49
Amount is: 9999.089 and formatted to: 9,999.08
Amount is: 0.19999 and formatted to: 0.19
Amount is: 123456.99999999 and formatted to: 123,456.99
2个回答

17

这应该足以获得结果。

String.format("%,.2f", amount.setScale(2, RoundingMode.DOWN)); 

2
输出取决于语言环境,因此可以使用 format(Locale.ENGLISH,"%,.2f", amount.setScale(2, RoundingMode.DOWN))。如果您将语言环境更改为 FRANCE,则会看到略有不同的格式。 - Pshemo

3

您应该使用 DecimalFormat

val df: DecimalFormat = DecimalFormat("#,##0.000")
df.decimalFormatSymbols = DecimalFormatSymbols(Locale.getDefault())
df.format(BigDecimal(123456,78)); //will output 123.456,78 - depending on Locale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接