NumberFormat does not like more than 340 decimal places

I want to format a double with a certain number of decimal places in Java. Currently my code is as follows:

    final NumberFormat format = NumberFormat.getInstance();
    format.setMinimumFractionDigits(decimalPlaces);
    format.setMaximumFractionDigits(decimalPlaces);
    format.setGroupingUsed(false);
    String s = format.format(value);

but when decimalPlacesgreater than 340, this method simply prints 340 digits and ignores the rest. Is there a way around this limitation?

In particular, in my case they are all 0s (and probably will be with any number after a certain point, since the accuracy is not so high), but it seems wrong to me that the function just silently ignores what I want, and does not throw an exception or something else.

Yes, I know that double cannot actually hold so many decimal places, but it is also true that int cannot contain any decimal places, but I can print it with some.

+4
source share
2 answers

The setMinimumFractionDigits documentation contains the following statement:

A particular subclass may impose an upper limit on this value corresponding to a formatted number type.

Most likely the subclass returned NumberFormat.getInstanceby DecimalFormat, which tells us in JavaDocs

To format numbers other than BigInteger and BigDecimal objects, the lower value newValue and 340 are used. Negative input values ​​are replaced with 0.

So, to solve your problem, convert your number to BigDecimalbefore formatting it.

+3
source

In the case of a double value, truncation occurs. Use / declare value asBigDecimal

Try this sample code:

    final NumberFormat format = NumberFormat.getInstance();
    format.setMinimumFractionDigits(355);
    format.setMaximumFractionDigits(400);
    format.setGroupingUsed(false);
    System.out.println(format.getMinimumFractionDigits());
    BigDecimal bd=new BigDecimal(10L);
    String s = format.format(bd);
    System.out.println(s.length());
    System.out.println(s);
0
source

Source: https://habr.com/ru/post/1672114/


All Articles