您可能可以使用MessageFormat,特别是其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
)
);
}
打印:
-876.123 negative
-0.1 negative
0.0 zero
0.5 0.500
100.0 1,00.000
123.45678 1,23.457
请注意,MessageFormat确实在幕后使用了DecimalFormat.从the documentation开始:
FORMAT TYPE: number
FORMAT STYLE: subformatPattern
SUBFORMAT CREATED: new DecimalFormat(
subformatPattern,
DecimalFormatSymbols.getInstance(getLocale())
)
因此,尽管间接地使用了DecimalFormat.如果出于某种原因禁止这样做,则必须自己检查特殊条件,因为DecimalFormat不会区分零.从the documentation:
DecimalFormat patterns have the following syntax:
06003
没有提供零的特殊模式的选项,因此没有DecimalFormat模式可以为您执行此操作.您可以进行if-check检查,也可以只让MessageFormat / ChoiceFormat为您完成检查,如上所示.