user3075268
user3075268

Reputation: 53

double to int conversion always results in 0

I am attempting to cast a java double into an int which is always resulting in 0. I have printed the values out to the console to try and get a better idea of what might be happening although it isn't helping.

4.849401383433042E-10 <- value stored as a double.

0 <- the result after attempting to cast to an int.

I am attempting to cast by int i = (int) myDouble;

Thanks.

Upvotes: 0

Views: 1315

Answers (3)

TWRaven
TWRaven

Reputation: 47

Try using the Integer class provided by Java.

Double dblObject = new Double(myDouble);

int cast = dblObject.intValue();

Upvotes: -2

rgettman
rgettman

Reputation: 178343

The value 4.849401383433042E-10 is similar to scientific notation. That value is equivalent to 4.849401383433042 * 10-10, or 0.0000000004849401383433042.

When you cast it to an int, the narrowing primitive conversion rules specify that the value is rounded towards 0 to yield an int, so the result is 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).

Without that E-10 part it would result in not 5, but 4.

Upvotes: 6

Steven Tchadenis
Steven Tchadenis

Reputation: 151

The value 4.849401383433042E-10 is equivalent to 0.0000000004849401383433042.

When this is cast to an integer, the value becomes 0. Remember that integer casting does not do any kind of rounding, they merely take what is before the decimal. For example, examine the following code.

double x = 9.99999;
int x_int = (int) x;

System.out.println("X is: " + x_int);

This prints out:

X is 9

Also to keep in mind is things like integer division. Examine the following code:

int i = 3 / 5;
double j = 3.0/5.0;

System.out.println("I is: " + i + "\n" + "J is: " + j);

This prints out:

I is: 1

J is: 1.4

Upvotes: 2

Related Questions