gpt4 book ai didi

java.text.DecimalFormat 为零时为空?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:17 26 4
gpt4 key购买 nike

当数字为零 (0) 时是否可以显示空白(空字符串)? (左边严格没有零)

最佳答案

您可以使用 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<{0,number,'#,#0.000'}}", num
)
);
}

这打印:

-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:

 Pattern:
PositivePattern
PositivePattern ; NegativePattern

没有为零提供特殊模式的选项,因此没有可以为您执行此操作的 DecimalFormat 模式。例如,您可以使用 if 检查,或者让 MessageFormat/ChoiceFormat 为您完成检查,如上所示。

关于java.text.DecimalFormat 为零时为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3001989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com