Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.text.DecimalFormat blank when zero?

Is it possible to show blank (empty string) when the number is zero (0)? (strict no zeros at left)

like image 700
Eduardo Avatar asked Jun 15 '26 16:06

Eduardo


1 Answers

You may be able to use MessageFormat, specifically its ChoiceFormat feature:

double[] nums = {
    -876.123, -0.1, 0, +.5, 100, 123.45678,
};
for (double num : nums) {
    System.out.println(
        num + " " +
        MessageFormat.format(
            "{0,choice,-1#negative|0#zero|0<{0,number,'#,#0.000'}}", num
        )
    );
}

This prints:

-876.123 negative
-0.1 negative
0.0 zero
0.5 0.500
100.0 1,00.000
123.45678 1,23.457

Note that MessageFormat does use a DecimalFormat under the hood. From the documentation:

FORMAT TYPE:       number
FORMAT STYLE:      subformatPattern
SUBFORMAT CREATED: new DecimalFormat(
                      subformatPattern,
                      DecimalFormatSymbols.getInstance(getLocale())
                   )

So this does use a DecimalFormat, albeit indirectly. If this, for some reason, is forbidden, then you must resort to checking for a special condition yourself, since DecimalFormat does not distinguish zero. From the documentation:

DecimalFormat patterns have the following syntax:

 Pattern:
         PositivePattern
         PositivePattern ; NegativePattern

There is no option to provide a special pattern for zero, so there is no DecimalFormat pattern that can do this for you. You can either have, say, an if-check, or just let MessageFormat/ChoiceFormat do it for you as shown above.

like image 140
polygenelubricants Avatar answered Jun 18 '26 06:06

polygenelubricants