Search code examples
javaandroidformattingbigdecimal

Format BigDecimal number with commas upto 2 decimal places


I want to format BigDecimal numbers with comma and 2 decimal places. If the decimal values in BigDecimal number are 0 then I want to remove the trailing zeros also. E.g Amount is 20000.00 and should be formatted to 20,000 Amount is 167.50 and should be formatted to 167.50 Amount is 20000.75 and should be formatted to 20,000.75

I have used this method-

public static String getNumberFormattedString(BigDecimal bigDecimal) {
        if (bigDecimal != null) {
            NumberFormat nf = NumberFormat.getInstance(new Locale("en", "IN"));
            nf.setMinimumFractionDigits(0);
            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);
            return nf.format(bigDecimal);
        }
        return "";
    }

This is not returning correct output for big decimal input 167.50. The formatted output is coming as 167.5


Solution

  • You can use NumberFormat for what you want. Here is the function I use:

       public static String GenerateFormat(Double value) {
            if (value == null) return "";
            NumberFormat nf = NumberFormat.getInstance(new Locale("de", "DE"));
            nf.setMinimumFractionDigits(0);
            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);
            return nf.format(value);
        }
    

    In this, you can see that I am providing Locale as a parameter for NumberFormat. Each country has its own number formatting standard, and what you want can be achieved with this locale new Locale("en", "US"). Inside setMaximumFractionDigits you can place how much of fraction digits you want, in your case it is 2.

    EDIT

    Because of your situation, try this:

       public static String GenerateFormat(Double value) {
            if (value == null) return "";
            NumberFormat nf = NumberFormat.getInstance(new Locale("de", "DE"));
            if (value%1 == 0) nf.setMinimumFractionDigits(0);
            else nf.setMinimumFractionDigits(2);
            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);
            return nf.format(value);
        }