为什么 Java BigDecimal 返回 1E+1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/925232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Java BigDecimal return 1E+1?
提问by parkr
Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation?
为什么这段代码有时会返回 1E+1 而对于其他输入(例如 17),输出不是以科学记数法打印的?
BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros();
System.out.println("value: " + bigDecimal);
回答by dfa
use bigDecimal.toPlainString():
BigDecimal bigDecimal = BigDecimal.valueOf(100000.0)
.multiply(BigDecimal.valueOf(100d))
.stripTrailingZeros();
System.out.println("plain : " + bigDecimal.toPlainString());
System.out.println("scientific : " + bigDecimal.toEngineeringString());
outputs:
输出:
plain : 10000000 scientific : 10E+6
回答by Jordan S. Jones
It's the implicit .toString()conversion that is happening when you pass the result into System.out.println().
这是隐含的.toString(),当你通过结果到正在发生转变System.out.println()。
回答by Michael Borgwardt
The exact rationale for the behaviour of BigDecimal.toString()is explained in the API docin great (and near incomprehensible) detail.
API 文档中详细BigDecimal.toString()解释了 的行为的确切原理(并且几乎无法理解)。
To get a consistent (and locale-sensitive) textual representation, you should use DecimalFormat.
要获得一致(和区域设置敏感)的文本表示,您应该使用DecimalFormat。
回答by newacct
It's basically because you don't have enough significant digits. If you multiply something that only has 1 significant digit with 100, then you get something with only 1 significant digit. If it shows "10" then that basically says that it has 2 significant digits. The way to show it only has 1 significant digit is to show "1 x 10^1".
这基本上是因为你没有足够的有效数字。如果你将只有 1 个有效数字的东西与 100 相乘,那么你会得到只有 1 个有效数字的东西。如果它显示“10”,那么基本上表示它有 2 个有效数字。显示它只有 1 个有效数字的方法是显示“1 x 10^1”。
The following two decimals have the same value (10), but different "scales" (where they start counting significant digits; the top has 2 sig figs, the bottom has 1):
以下两个小数具有相同的值 (10),但不同的“刻度”(它们开始计算有效数字;顶部有 2 个无花果,底部有 1 个):
System.out.println(new BigDecimal(BigInteger.TEN, 0)); // prints 10
System.out.println(new BigDecimal(BigInteger.ONE, -1)); // prints 1E+1

