0

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?

  • Is this for a school project? If not, stop wasting your time and use a `NumberFormat`. If it is, let us know and we can try to guide you in fixing your code. – Ian McLaird Dec 16 '14 at 15:56

3 Answers3

2

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

Aestel
  • 409
  • 8
  • 12
1

Try setting the minimum fraction digits along with maximum fraction digits.

f.setMaximumFractionDigits(decimalDigits);
f.setMinimumFractionDigits(decimalDigits);

Java Doc for DecimalFormat

RogerRoger
  • 105
  • 1
  • 1
  • 7
0

For DecimalFormat you can use the constructor that requires a pattern. In your patterns a # symbol represents a zero or blank if the zero doesn't need to be printed, like after a decimal. If you want the zero to be printed then you replace the # with a 0. For example:

#,###,###.##

Will only show a zero if it is require like 0.54 or 0.3 but not in whole numbers.

#,###,###.00

will show the trailing zeros up to 2 decimal places like 2.50 or 79.00.

markbernard
  • 1,412
  • 9
  • 18