Android Float To Int

25,724

Solution 1

Uhhh, yeah, how about:

int y = (int)event.getY();

You see getY() only returns a float for devices that have a sub-pixel accuracy.

Solution 2

Using

Math.round(yourFloat);

is better than

(int)yourFloat;

It is all about precision. If you use (int) you'll just get numbers after the point removed. If you use Math, you'll get a rounded number. It doesn't seems like a big deal.For example, if you try to round something like 3.1, both methods would produce the same result - 3.

But take 3.9 or 3.8. It's practically 4, yet

(int)3.9 = 3

whereas

Math.round(3.9) = 4

Share:
25,724
shaneburgess
Author by

shaneburgess

Updated on November 16, 2020

Comments

  • shaneburgess
    shaneburgess over 3 years

    Why is this so hard to find out?

    public boolean onTouch(View v, MotionEvent event)
    

    I need to convert float event.getY() to an int.

    Is this possible?

    event.getY().intValue() will not work at all.

    Any ideas?