我有一个 BigDecimal 数,我只考虑它的两个小数位,所以我截断它使用:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN)
现在我想把它打印成字符串,但是如果它是0,那么移除小数部分,例如:
1.00-> 1
1.50-> 1.5
1.99-> 1.99
我试过使用 Formatter,formter.format,但我总是得到2个小数位。
我该怎么做呢? 也许是处理 bd.toPlainString ()中的字符串?
Use stripTrailingZeros().
stripTrailingZeros()
This article should help you.
I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.
DecimalFormat
BigDecimal
String
The code is something like this:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN); DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(2); df.setMinimumFractionDigits(0); df.setGroupingUsed(false); String result = df.format(bd);
new DecimalFormat("#0.##").format(bd)
The below code may help you.
protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) { final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); numberFormat.setGroupingUsed(true); numberFormat.setMaximumFractionDigits(2); numberFormat.setMinimumFractionDigits(2); return numberFormat.format(input); }
If its money use:
NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)