仅具有负指数的 Java DecimalFormat

标签 java formatting decimalformat

我无法使用以下属性定义 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/

相关文章:

java - 如何在不调用execSQL的情况下删除SQLite表IF EXISTS?

java - 使用 HashMap 通过迭代更新值来计算 map 是一种好习惯吗?

java - 乘以 DecimalFormat 数字(不再正确舍入)

java - 如何四舍五入到小数点第二位最接近的 5

java - 基本 Java 继承练习

java - 如何在 Android 8 和 9 上添加设置了 HttpProxy 的 WifiConfiguration

C++ 文本文件读取

css - 如何解决PhpStorm中的CSScomb错误?

java - Java DecimalFormat 的问题

java - 格式,java中double小数点后2位,integer小数点后0位