4

Trying to figure out why the following code is not outputting expecting results. Please advise. Thank you.

    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");
        }
    }
}

Output:

 987.12346 // Expected 987.12345 not 987.12346
987.123456
Rami Del Toro
  • 1,130
  • 9
  • 24
  • Why did you expect that? – Sotirios Delimanolis Oct 17 '14 at 01:11
  • `NumberFormat` is rounding up. See http://stackoverflow.com/questions/3833137/how-to-make-number-format-not-to-round-numbers-up – Denise Oct 17 '14 at 01:13
  • Sotiri, I was expecting that because, I was under the assumption that since I set the max Fraction digits to 5, the object should return 5 unchanged digits, however was not aware that a rounding was occurring. – Rami Del Toro Oct 17 '14 at 15:11
  • 1
    I'm going over the same book Rami (SCJP Sun Certified Programmer for Java 6) and had the exact same question. Thank you for helping clarify that it is rounding. For anyone else looking at this question, this can be one asked on the Java Certificate test/ exam. Study up! – PGMacDesign Mar 23 '15 at 23:27

1 Answers1

2

Your second print doesn't format the double you've parsed.

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

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

nf.setMaximumFractionDigits(5);
nf.setRoundingMode(RoundingMode.DOWN);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249