【发布时间】:2018-04-05 14:23:29
【问题描述】:
我无法使用以下属性定义 DecimalFormat 实例(在 Java1.8 中):
- 仅当指数为负时才使用科学记数法(指数)。
- 最多显示 4 个重要位置,即末尾没有 0。
(如果需要,我可以在不满足第二个属性的情况下生活。)
目的是将双精度数转换为字符串,即使用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]));
}
【问题讨论】:
-
你不能使用两个格式化程序吗?使用您已有的格式,使用正则表达式检查小数是否为负数,如果不是,则使用不使用科学记数法的其他格式。
-
@Diasiare 问题是当前的格式化程序在整个代码中都使用了。到目前为止,最好的选择是简单地重新定义它......第二好的选择是定义在已知事物“大”的情况下使用的第二个格式化程序。但是,这需要一些时间......
标签: java formatting decimalformat