Android Float 到 Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3024624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:20:39  来源:igfitidea点击:

Android Float To Int

androidfloating-pointinteger

提问by shaneburgess

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.

我需要转换float event.getY()为int。

Is this possible?

这可能吗?

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

event.getY().intValue()根本不会工作。

Any ideas?

有任何想法吗?

回答by CaseyB

Uhhh, yeah, how about:

呃,是的,怎么样:

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

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

您会看到getY()仅返回具有子像素精度的设备的浮点数。

回答by Oleksandr Firsov

Using

使用

Math.round(yourFloat);

Math.round(yourFloat);

is better than

(int)yourFloat;

(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.

这一切都与精度有关。如果您使用,(int)您将在删除点后获得数字。如果您使用Math,您将得到一个四舍五入的数字。这似乎没什么大不了的。例如,如果您尝试对 3.1 之类的东西进行四舍五入,则两种方法都会产生相同的结果 - 3。

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

但是取 3.9 或 3.8。它实际上是 4,但

(int)3.9 = 3

(int)3.9 = 3

whereas

然而

Math.round(3.9) = 4

Math.round(3.9) = 4

回答by Makvin

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

Math.round() 会将浮点数四舍五入到最接近的整数。

回答by Matthew Flaschen

Just cast it:

只需投射它:

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