Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

omegasyphon

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

This topic is 5993 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!