0

Am I missing something here? According to the doc, String.format "f" use HALF_UP rounding algorithm. So shouldn't the following two print the same result?

DecimalFormat df = new DecimalFormat("#0.0");
double num = 3.55;
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(num));             // prints "3.5"
System.out.println(String.format("%.1f", num)); // prints "3.6"
joe
  • 63
  • 1
  • 8
  • 2
    `double num = 3.55` is already inexact, possibly something like `3.549999999999`. Not `DecimalFormatter`'s fault. – user207421 Mar 23 '18 at 00:40
  • would love to hear more in depth explanation. e.g 1.55 would result 1.6, not 1.5. Also according to documentation String.format use HALF_UP, so my setting rounding mode of DecimalFormat to HALF_UP, shouldn't they produce the same result? This is also from the doc of HALF_UP "Note that this is the rounding mode that most of us were taught in grade school". – joe Mar 23 '18 at 01:06
  • there is a deep explanation about double precision https://en.wikipedia.org/wiki/IEEE_754-1985 – Yu Jiaao Mar 23 '18 at 01:24
  • @EJP I realised that my question wasn't very clear, so I've rephrased it. So now this is more about how two different api treat double than how double is represented in binary. – joe Mar 23 '18 at 01:32
  • 1
    I don't see the question answered in said duplicate. – user unknown Mar 23 '18 at 01:49

0 Answers0