简体   繁体   中英

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)

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.

You can use String.format method:

int num1=0;
int num2=33;
string str1 = (num1!=0) ? String.format("%3d", num1) : "   ";
string str2 = (num2!=0) ? String.format("%3d", num2) : "   ";

System.out.println("("+str1+")");  // output: (   )
System.out.println("("+str2+")");  // output: ( 33)

syntax of format is very similar to c printf (for this basic use)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM