Java 如何将浮点数转换为整数:android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20374547/
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-13 01:28:01  来源:igfitidea点击:

How to convert float to int : android

java

提问by Aswathy

float NormValue = value*80 ;
float color = Color.argb(0xFF, NormValue, 0, 0);

This is a part of my code. This variable (NormValue) stores the result in float . But in second line i cannot use this variable since it has to be converted to int. How can i do it. Any help?

这是我的代码的一部分。此变量 (NormValue) 将结果存储在 float 中。但在第二行我不能使用这个变量,因为它必须转换为 int。我该怎么做。有什么帮助吗?

回答by KethanKumar

Try this:

尝试这个:

float NormValue = value*80 ;
int temp = (int)NormValue;
float color = Color.argb(0xFF, temp, 0, 0);

回答by laalto

Depends on the scale of your NormValue.

取决于你的规模NormValue

Normally, a simple type cast would do:

通常,一个简单的类型转换会做:

(int)NormValue

But you may want to scale the NormValueto the range 0..255 first since Color.argb()just uses the least significant 8 bits of the int values passed in.

但是您可能希望NormValue首先将范围缩放到 0..255,因为Color.argb()只使用传入的 int 值的最低有效 8 位。

回答by brunch875

Android is java, right? You can simply cast it to int like this.

安卓是java吧?你可以像这样简单地将它转换为 int 。

float f=0.2;
int i;

i = (int)f;

回答by AndroidHacker

Try this.

尝试这个。

Convert it to string

将其转换为字符串

String.valueOf(value);

and then convert it to integer

然后将其转换为整数

Integer.valueOf(string);

You can also try casting it to int

您也可以尝试将其转换为 int

Int i =  (int) your_float_value

回答by Alex

You really need to use float in the first place? You have two options:
1. Use casting int normInt = (int)NormValue; but here you have to be prepared that you will loose the decimal points. eg: 8.61 will be 8
2. The second way to first round the NormValue then use casting.

你真的需要首先使用 float 吗?您有两个选择:
1. 使用强制转换 int normInt = (int)NormValue; 但在这里你必须准备好你会丢失小数点。例如:8.61 将是 8
2。第二种方法首先舍入 NormValue 然后使用强制转换。

回答by Hariharan

Try this..

尝试这个..

No need to typecastfloatto intjust use Math.round()

无需类型转换float即可int使用Math.round()

float NormValue = value*80 ;
float color = Color.argb(0xFF, Math.round(NormValue), 0, 0);

回答by Kappys

You can search in this post, your solution is there: Java: (int)(float)Float.valueOf(s) or Float.valueOf(s).toInt()

你可以在这篇文章中搜索,你的解决方案在那里: Java: (int)(float)Float.valueOf(s) or Float.valueOf(s).toInt()

If you want more information, you can ask me :)

如果你想了解更多信息,你可以问我:)