Is it possible to show blank (empty string) when the number is zero (0)? (strict no zeros at left)
+2
A:
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.
polygenelubricants
2010-06-09 04:44:11
I really need to use java.text.DecimalFormat
Eduardo
2010-06-09 06:41:54