我想在 Java 中格式化一个具有一定小数位数的 double 。我的代码目前看起来像这样:
final NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(decimalPlaces);
format.setMaximumFractionDigits(decimalPlaces);
format.setGroupingUsed(false);
String s = format.format(value);
但是当 decimalPlaces
大于 340 时,此方法只打印 340 位而忽略其余部分。有没有办法解决此限制?
特别是在我的例子中,它们都是 0(并且可能在某个点之后是任何数字,因为精度不是那么高)但我觉得这个函数只是默默地忽略了我想要的而不是抛出异常或其他东西。
是的,我知道 double 实际上不能容纳那么多小数位,但 int 也确实不能容纳任何小数位,但我可以用一些来打印它。
最佳答案
setMinimumFractionDigits 的文档包含此语句:
The concrete subclass may enforce an upper limit to this value appropriate to the numeric type being formatted.
很可能 NumberFormat.getInstance
返回的子类是 DecimalFormat
,它告诉我们 JavaDocs
For formatting numbers other than BigInteger and BigDecimal objects, the lower of newValue and 340 is used. Negative input values are replaced with 0.
因此,为了解决您的问题,请在格式化之前将您的数字转换为 BigDecimal
。
关于java - NumberFormat 不喜欢超过 340 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753014/