我无法使用以下属性定义 DecimalFormat
实例(在 Java1.8 中):
- 仅当指数为负数时才使用科学计数法(指数)。
- 最多显示 4 个有效位,即末尾没有 0。
(如果有必要,我可以在不满足第二个属性(property)的情况下生活。)
目的是将 double 转换为字符串,即使用format
方法。以下是一些示例中所需的行为:
Representation of 9: 9
Representation of 9.0: 9
Representation of 9876.6: 9877
Representation of 0.0098766: 9.877E-3
Representation of 0.0000000098766: 9.877E-9
如果我定义 DecimalFormat df = new DecimalFormat("#.###E0");
,则给出
Representation of 9: 9E0
Representation of 9.0: 9E0
Representation of 9876.6: 9.877E3
Representation of 0.0098766: 9.877E-3
Representation of 0.0000000098766: 9.877E-9
前三种情况是错误的。不允许使用 DecimalFormat("#.###E#")
或 DecimalFormat("#.###E")
之类的内容 (IllegalArgumentException
) > 被抛出)。
下面给出了生成输出的代码。
DecimalFormat df = new DecimalFormat("#.###E0");
double[] xs = new double[] {9, 9.0, 9876.6, 0.0098766, 0.0000000098766};
String[] xsStr = new String[] {"9", "9.0", "9876.6", "0.0098766", "0.0000000098766"};
for(int i = 0; i < xs.length; i++) {
System.out.println("Representation of " + xsStr[i] + ": " + df.format(xs[i]));
}
最佳答案
您可以尝试使用 if 语句来检查数字是否小于 1。
if (xs < 1) {
System.out.println("Representation of " + xsStr[i] + ": " + df.format(xs[i]));
}
else {
System.out.println("Representation of " + xsStr[i] + ": " + xs[i];
}
另一种选择是使用三元运算符。
System.out.println("Representation of " + xsStr[i] + ": " + xs[i] < 1 ? df.format(xs[i]) : xs[i]);
这个答案很好地解释了它是如何工作的。 https://stackoverflow.com/a/25164343/
关于仅具有负指数的 Java DecimalFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674786/