-4

A project I have requires the movement of a player at a coordinate using getX and getY, however, I am confused on how to convert getX and getY from a double to an int so i can play them in the drawing panel.

2 Answers2

0

You want to cast your double as an int but you need to be careful about how you cast because if you want your movement to be accurate you want values of x.5 and over to be rounded up and values below x.5 to be rounded down.

Casting will always round down so a good way to properly round is to add .5 to all of your doubles before you cast to an int.

Here are a few examples

double = 1.1
int (double) = 1

double = 1.7
int (double) = 1 \\ Note that we will likely want this to be 2

Using our method lets see how these 2 doubles would be casted

double = 1.1
double + .5 = 1.6
int (double) = 1

double 1.7 = 1.7
double + .5 = 2.2
int (double) = 2

Note that now our doubles that are above x.5 will be rounded up properly.

Jay
  • 157
  • 2
  • 11
0

Just casting to int will truncate the double. So you need to specify what result you really want before you decide how to get the int. For example, if the double value is 2.999, do you want your int to be 2 or 3?

If you want the closest int (3 above), then use Math.round(d) which returns a long.

FredK
  • 4,094
  • 1
  • 9
  • 11