有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java NumberFormat不喜欢超过340个小数位

我想在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也不能保存任何小数位,但我可以打印一些


共 (1) 个答案

  1. # 1 楼答案

    {a1}的文档包含以下语句:

    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