How to convert float to int : android

Viewed 39027
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?

7 Answers

Try this..

No need to typecast float to int just use Math.round()

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

Depends on the scale of your NormValue.

Normally, a simple type cast would do:

(int)NormValue

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

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 i =  (int) your_float_value

Try this:

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

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

float f=0.2;
int i;

i = (int)f;

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.

Related