ant2009
ant2009

Reputation: 22486

Convert a float to int

Android Studio 0.5.2

Hello,

I have a random float value that I want to convert to an int.

The float could have a random number between -9.4182062E-9 to 9.593071E-8.

I just want to get the positive int number so if the number is negative i.e. -5.5115866E-8 it should just return 5. I have used the Math.abs for this.

I have tried the following:

int accel =  (int)Math.abs(randomAccel);

However, accel keeps giving me a zero no matter what value randomAccel is.

Many thanks for any suggestions,

Upvotes: 0

Views: 2478

Answers (4)

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

import static java.lang.Math.*;

Convert part:

double input =-5.485747E-5; //for example
double tmp = abs(input);
tmp *= pow(10, abs(floor(log10(tmp))));
int out = (int) tmp;
System.out.println(out);

output:

5

Upvotes: 1

Thomas
Thomas

Reputation: 1420

Your negative number -5.485747E-5 finish by E-5 meaning that it is -0.0000548574 So the absolute value is 0.0000548574.

So Math.abs(-0.0000548574) is 0.0000548574

(int)0.0000548574 is 0

result is 0

Are your sure your code is responding 0 no matter the value of random? Check the number you are trying to convert.

You should unit test your code with your values.

Upvotes: 3

clcto
clcto

Reputation: 9648

 int accel = (int)Math.abs(randomAccel);

This line performs 3 steps

  1. Get the absolute value of randomAccel
  2. Cast the value to an int (floating point numbers are truncated)
  3. Assign the int value to accel

Now lets look what happens when the input is in the range [-9.4182062E-9,9.593071E- 8] (By the way -5.485747E-5 is not in this range.)

Input value -9.4E-9 = -0.0000000094

1. -9.4E-9 converted to 9.4E-9
2. 9.4E-9 cast to int, fractional part is removed. Value is 0
3. 0 is assigned to `accel`

If you just want to most significant digit, you could multiply by 10^8 and see if that value is greater than 0, if it is then trucate, else multiply by 10 then truncate:

int accel = 0;
r = Math.abs( randomAccel ) * 100000000;
if( r >= 10 ) {/* error out of range */}
else if( r > 0 ) accel = (int)r;
else
{
    r *= 10;
    accel = (int)r;
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 425033

Your random number range has very small a magnitude (negative exponents) - importantly it is less than +/-1. When float is cast to int, all fractional parts are truncated, thus every number in your range, after setting the sign to positive, will result in 0 if cast to int.

It seems like you want to ignore the exponent of your numbers. One way to do that would be:

int accel = Integer.parseInt(String.valueOf(randomAccel).replaceAll("-?(\\d+).*", "$1"));

Upvotes: 1

Related Questions