I have a BigDecimal number and i consider only 2 decimal places of it so i truncate it using:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN)
Now I want to print it as String but removing the decimal part if it is 0, for example:
1.00 -> 1
1.50 -> 1.5
1.99 -> 1.99
I tried using a Formatter, formatter.format but i always get the 2 decimal digits.
How can I do this? Maybe working on the string from bd.toPlainString()?
This question is related to
java
formatting
bigdecimal
Use stripTrailingZeros()
.
This article should help you.
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)
new DecimalFormat("#0.##").format(bd)
Source: Stackoverflow.com