Search code examples
javadecimalbigdecimal

How can I fix this method that convert Number in String to show the correct number of decimal digits?


I have the following problem.

I am using this method to convert a Number (as a BigDecimal) to a formatted string:

/**
 * @param n il Number da formattare
 * @param thou_sep separator for hundreds
 * @param dec_sep  separator for decimal digits
 * @param number of decimal digits to show
 * @return a string representing the number
 * @author Andrea Nobili
 */
public static String getFormattedNumber(Number n, String thou_sep, String dec_sep, Integer decimalDigits) {

    if (n == null) return "";

    double value = n.doubleValue();

    if (decimalDigits != null && decimalDigits < 0)
        throw new IllegalArgumentException("[" + decimalDigits + " < 0]");

    DecimalFormatSymbols s = new DecimalFormatSymbols();
    if (thou_sep != null && thou_sep.length() > 0) {
        s.setGroupingSeparator(thou_sep.charAt(0));
    }
    if (dec_sep != null && dec_sep.length() > 0) {
        s.setDecimalSeparator(dec_sep.charAt(0));
    }
    DecimalFormat f = new DecimalFormat();
    f.setDecimalFormatSymbols(s);
    if (thou_sep == null || thou_sep.length() == 0) {
        f.setGroupingUsed(false);
    }
    if (decimalDigits != null) {
        f.setMaximumFractionDigits(decimalDigits);
    }
    f.setMaximumIntegerDigits(Integer.MAX_VALUE);
    String formattedNumber = f.format(value);
    return ("-0".equals(formattedNumber)) ? "0" : formattedNumber;
}

For example if I call something like:

utilityClass.getFormattedNumber(57.4567, null, ",", 2)

I obtain the string 57,45

Ok, this work fine.

My problem is that if I try to perform it with a number having not decimal digits (for example passing the value 57 it return the String 57. I want that in this case it return the string 57.00 (because I have specified that I want 2 decimal digits in the input parameter of this method)

How can I fix this issue and obtain the correct number of decimal digits?


Solution

  • You can use DecimalFormat setMinimumFractionDigits and set it to the same as the maximum.