3

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?

4 Answers 4

17

Uhhh, yeah, how about:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

It always returns a float. Maybe you mean the float represents an integer?
Correct. On devices that don't have sub-pixel accuracy the float is always something like 235.0. You can just cast to an int to get the pixel value.
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

6 Comments

What about (int)(some_float + 0.5) ?
Result depends on value of some_float. If it has 1 decimal after point, like x.5 to x.9, then result will be x + 1 (x.5 + 0.5 = x+1), if x.0 to x.04 - just x (x.4 + 0.5 = x.9). But still, this won't work as Math.round. 1.46 + 0.5 = 1.96. (int)1.96 = 1. In that case, to get precise result, you would need to have some_float + 0.5555555555...infinity
I don't see the problem. I would expect 1.46 to be rounded to 1 as it is less than 1.5.
I think you are misunderstanding how rounding works. Rounding is not recursive. If you want to round to the nearest increment, then all that is done is a comparison with the half-way point. If the input is larger, round up. If it is smaller, round down. If it is equal, then generally accepted practice is to round up. 1.46 is closer to 1 than 2, so if you are rounding to the closest integer, then you will round it to 1.
Yeah, Math.round(1.46) returns 1. See ideone.com/Lj43Dh .
|
0

Just cast it:

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

1 Comment

This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.
0

Math.round() will round the float to the nearest integer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.