shaneburgess
shaneburgess

Reputation: 15912

Android Float To Int

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?

Upvotes: 3

Views: 26130

Answers (4)

Makvin
Makvin

Reputation: 3629

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

Upvotes: 0

Oleksandr Firsov
Oleksandr Firsov

Reputation: 1478

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

Upvotes: 2

Matthew Flaschen
Matthew Flaschen

Reputation: 285047

Just cast it:

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

Upvotes: 0

CaseyB
CaseyB

Reputation: 25058

Uhhh, yeah, how about:

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

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

Upvotes: 17

Related Questions