Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

JavaFormattingBigdecimal

Java Problem Overview


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()?

Java Solutions


Solution 1 - Java

I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

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);

Solution 2 - Java

new DecimalFormat("#0.##").format(bd)

Solution 3 - Java

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);
}

Solution 4 - Java

Use stripTrailingZeros().

This article should help you.

Solution 5 - Java

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionres1View Question on Stackoverflow
Solution 1 - Javares1View Answer on Stackoverflow
Solution 2 - JavaFederico CattozziView Answer on Stackoverflow
Solution 3 - JavaParamesh KorrakutiView Answer on Stackoverflow
Solution 4 - JavalrAndroidView Answer on Stackoverflow
Solution 5 - JavaHeisenbergView Answer on Stackoverflow