NumberFormat: setMaximumFractionDigits - does not give the expected results

Trying to find out why the following code does not display the expected results. Please advise. Thank.

    import java.text.*;

public class Test {
    public static void main(String[] args) {
        String s = "987.123456";
        double d = 987.123456d;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(5);
        System.out.println(nf.format(d) + " ");
        try {
            System.out.println(nf.parse(s));
        } catch (Exception e) {
            System.out.println("got exc");
        }
    }
}

Conclusion:

 987.12346 // Expected 987.12345 not 987.12346
987.123456
+4
source share
1 answer

The second print will not format the doubleone you analyzed.

// System.out.println(nf.parse(s));
System.out.println(nf.format(nf.parse(s))); // <-- 987.12346

To get the output you asked, you can add a call NumberFormat#setRoundingMode(RoundingMode)- something like

nf.setMaximumFractionDigits(5);
nf.setRoundingMode(RoundingMode.DOWN);
+2
source

All Articles