0

Which of the following rounding mode is followed by casting a double to an int?

Result of rounding input to one digit with the given rounding mode

Input                                                   HALF_EVEN
Number  UP      DOWN    CEILING FLOOR   HALF_UP HALF_DOWN       UNNECESSARY
5.5     6       5       6       5       6       5       6       throw ArithmeticException
2.5     3       2       3       2       3       2       2       throw ArithmeticException
1.6     2       1       2       1       2       2       2       throw ArithmeticException
1.1     2       1       2       1       1       1       1       throw ArithmeticException
1.0     1       1       1       1       1       1       1       1
-1.0    -1      -1      -1      -1      -1      -1      -1      -1
-1.1    -2      -1      -1      -2      -1      -1      -1      throw ArithmeticException
-1.6    -2      -1      -1      -2      -2      -2      -2      throw ArithmeticException
-2.5    -3      -2      -2      -3      -3      -2      -2      throw ArithmeticException
-5.5    -6      -5      -5      -6      -6      -5      -6      throw ArithmeticException

I know that it's not related to casting primitives the enum I have quoted, however the table surely covers the way that a double gets downacasted to an int. Which one of the list does that? Thanks in advance.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Rollerball
  • 12,618
  • 23
  • 92
  • 161
  • to anyone interested in reading the table properly, click on the link "rounding mode" above posted – Rollerball Sep 12 '13 at 13:31
  • Interesting that with all those rounding modes, they didn't include floor(x+0.5), which I'd expect to be more often useful than half_up or half_down (in graphics, one should generally pick a rounding mode such that round(x+1) = round(x)+1 for all values of x where round(x)+1 is representable. – supercat Nov 01 '13 at 19:56

1 Answers1

3

Which of the following rounding mode is followed by casting a double to an int?

It simply truncates towards zero - is represented by the confusingly-named DOWN in your question.

From section 5.1.3 of the JLS:

A narrowing conversion of a floating-point number to an integral type T takes two steps:

In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

  • If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.

  • Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

[ ... ]

(The rest isn't relevant to the question.)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194