[java] casting doubles to integers how do u do it?

Started by
4 comments, last by omegasyphon 22 years, 1 month ago
alright i dont understand why i cant cast a double as an integer and i cant get it to work. the following lines read in a an object and convert to a double
  
if (myTokenizer != null && myTokenizer.ttype == myTokenizer.TT_NUMBER)
   returnValue = new Double(myTokenizer.nval);
  
now why doesnt this work Integer value = new Integer(returnValue);
Advertisement
Your first problem is that you are trying to pass the constructor of an Integer a Double Object. The Integer constructor only takes a int or String as it''s constructor. Also, note that you are technically not casting anything at all. You cannot cast a Double object to Integer object (Integer i = (Integer)new Double(2341.34d) would not work.

This is how you might want to do it:

if (myTokenizer != null && myTokenizer.ttype == myTokenizer.TT_NUMBER) returnValue = new Double(myTokenizer.nval);

Integer i = new Integer(returnValue.intValue());

You might want to check if these statements are throwing any Exceptions by placing it all in a try catch block. That way you can debug a little easier.
what''s wrong with

int i = (int) someDoubleValue;

??
_______________________ http://mill.3dfxsweden.net
Because if you read the code you will notice that he is creating a Double object not an intrinsic double type. You should not (and cannot) cast a Double object to an Integer object (object being the key word here). Unless myTokenizer.nval is already a double then you could do : int i = (int)myTokenizer.nval;
aha, my mistake
_______________________ http://mill.3dfxsweden.net
ok thanks, this worked

Integer i = new Integer(returnValue.intValue());

This topic is closed to new replies.

Advertisement