Java format BigDecimal numbers with comma and 2 decimal place

亡梦爱人 提交于 2019-12-01 16:08:34

问题


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

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

回答1:


This should be enough to get the results.

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



回答2:


You should use 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


来源:https://stackoverflow.com/questions/26101918/java-format-bigdecimal-numbers-with-comma-and-2-decimal-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!