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

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

The answer is


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)

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to bigdecimal

How to use comparison operators like >, =, < on BigDecimal Convert string to BigDecimal in java Adding up BigDecimals using Streams Rounding Bigdecimal values with 2 Decimal Places How can I parse a String to BigDecimal? Rounding BigDecimal to *always* have two decimal places BigDecimal to string How to multiply a BigDecimal by an integer in Java How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP? Convert double to BigDecimal and set BigDecimal Precision