Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #34482

Re: double-to-int conversion without a cast

Newsgroups comp.lang.java.programmer
Date 2016-06-05 16:57 -0700
References <conversion-20160225020052@ram.dialup.fu-berlin.de> <im42lbdcl9ar0gsr5kdp2512ri1f86ovv5@4ax.com> <nirnit$quc$1@dont-email.me> <nirsr2$ib0$1@dont-email.me>
Message-ID <c3e14960-4c28-4e7c-9921-2d54549b507e@googlegroups.com> (permalink)
Subject Re: double-to-int conversion without a cast
From bursejan@gmail.com

Show all headers | View raw


This code:

    public static void main(String[] args) {
        double d = Math.PI*100;
        int x = (int)d;
        System.out.println("x="+x);
    }

Prints:

    x=314

vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Basically you get zero for NaN, min_integer for underflow
and max_integer for overflow.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See also:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3
- double to byte, short, char, int, long, or float

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:

    If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

    Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

Otherwise, one of the following two cases must be true:

    The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

    The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Re: double-to-int conversion without a cast Roedy Green <inquiry@mindprod.com> - 2016-06-02 22:18 -0700
  Re: double-to-int conversion without a cast Martin Gregorie <martin@address-in-sig.invalid> - 2016-06-03 10:53 +0000
    Re: double-to-int conversion without a cast Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-06-03 08:22 -0400
      Re: double-to-int conversion without a cast bursejan@gmail.com - 2016-06-05 16:57 -0700

csiph-web