Java.text.DecimalFormat empty when zero?

Is it possible to show an empty (empty string) when the number is zero (0)? (strictly without zeros on the left)

+3
source share
2 answers

Perhaps you can use it MessageFormat, in particular ChoiceFormat:

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
        )
    );
}

Fingerprints:

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

Please note that MessageFormatuses DecimalFormatunder the hood. From the documentation :

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

Thus, it uses DecimalFormat, albeit indirectly. If this is forbidden for some reason, then you should resort to checking an individual condition, since it DecimalFormatdoes not distinguish zero. From the documentation :

DecimalFormat templates have the following syntax:

 Pattern:
         PositivePattern
         PositivePattern ; NegativePattern

, DecimalFormat, . , , if -check, MessageFormat/ChoiceFormat , .

+5

String.format:

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)

c printf ( )

0

Source: https://habr.com/ru/post/1749120/


All Articles