【问题标题】:Java DecimalFormat with only negative exponents只有负指数的 Java DecimalFormat
【发布时间】: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


【解决方案1】:

您可以尝试使用 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/

【讨论】:

    【解决方案2】:

    我认为您无法使用普通的 DecimalFormatter 类来实现您的目标。如果一切都使用DecimalFormatter 的相同实例,那么您可能可以继承DecimalFormatter,然后在覆盖的format 方法中应用类似于tristan 的答案。

    如果你这样做,请确保 parse 方法没有在任何地方使用,或者如果它确保也覆盖它。

    【讨论】:

    • 哦,这实际上已经足够了。这个子类可以有两个常用的DecimalFormatter 字段,而被覆盖的format 将简单地选择适当的一个并在其上调用标准格式。
    • 其实扩展DecimalFormat是没有必要的……这样也可以避免使用parse方法可能出现的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多