Java 格式 BigDecimal 数字,带逗号和 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26101918/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:17:10  来源:igfitidea点击:

Java format BigDecimal numbers with comma and 2 decimal place

javaformattingdecimalbigdecimal

提问by AmbGup

I want to format BigDecimal Numbers with comma and 2 decimal points. e.g.

我想用逗号和 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

回答by AmbGup

This should be enough to get the results.

这应该足以得到结果。

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

回答by Ciprian

You should use DecimalFormat:

你应该使用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