0

In my Java programming textbook, a section reads, "Note any double value x can be rounded up to an integer using (int) (x + 0.5)."

Is this true?

If 3.4 is inserted in for x, the value will return 3 and not round up since the integer data type rounds down. Maybe I'm just not understanding it correctly.

I've pasted an image of the section to provide more context.

Thanks in advance.

Saravana
  • 12,647
  • 2
  • 39
  • 57
  • If 3.4 is inserted, you add 0.5 to produce 3.9 which is then rounded up to 4. Likewise, if x is 3.9 you add 0.5 to produce 4.4, which is rounded down to 4. Either case, x is rounded up to the closest Integer. – Zachary Dec 18 '17 at 02:40
  • 3.9 rounded is 4 but I thought the (int) rounds it down in the Java programming language –  Dec 18 '17 at 02:56
  • My bad, I thought you were asking for an explanation why. It is true that the (int) cast the decimal part of the integer will be truncated, having the same affect as rounding down. – Zachary Dec 18 '17 at 03:02
  • Why would you expect 3.4 to round UP? There's no system in which 3.4 rounds UP to 4. This is the point of adding 0.5 and then truncating. Fractional values less than 0.5 will be rounded DOWN by truncation, but values 0.5 or greater will "round" UP. There will be anomalies at exactly .5 because of how floating point works. Read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) and [Is Floating Point Broken?](https://stackoverflow.com/q/588004/18157) – Jim Garrison Dec 18 '17 at 03:14
  • Your book is wrong, not only in that sentence but also in the following sentence where it uses the incorrect `((x+0.5)/100)*100` technique, refuted [here](https://stackoverflow.com/a/12684082/207421). – user207421 Dec 18 '17 at 03:20

1 Answers1

0

Note any double value x can be rounded up to an integer using (int) (x + 0.5)

This is true in theory, and would be true in practice if floating point numbers had infinite precision.

In theory:

 value    value+0.5    (int)(value+0.5)
  3.1       3.6              3
  3.499     3.999            3
  3.5       4.0              4
  3.501     4.001            4

In reality, things are not quite so neat, since floating point has limited precision you can get into situations such as this:

actual value     stored as    value+0.5    (int)(value+0.5)
123123.49999      12123.5       12124.0        12124
123123.50000      12123.5       12124.0        12124
123123.50001      12123.5       12124.0        12124

where the first value cannot be represented as a float and the nearest float is 12123.5, causing the unexpected result.

Further reading:

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190