-2

So I'm making a little app for myself and everything has been fine until now, I have no idea what I could have done but my answers are all coming out as whole numbers when I need decimal answers.

the code:

public float NumberCalc(){
    float number1 = 255/100;
    float number2 = ((5/366)*100);
    float finalNumber =(number1*number2);
    return finalNumber;
}

So I get 2.0 for number1 & 0.0 for number2 and I'm stumped

Can anyone shed some light on this scenario?

ashatte
  • 5,442
  • 8
  • 39
  • 50
Russell Cargill
  • 270
  • 1
  • 6
  • 19

3 Answers3

4

You are performing integer division and storing the result as floats.

255/100 results in 2 integer, saved as a float 2.0 To avoid this you can either specify the division as float by integer or integer by float division 255.0/100 or 255/100.0 or 255f. The same applies to number2

Geobits
  • 22,218
  • 6
  • 59
  • 103
arynaq
  • 6,710
  • 9
  • 44
  • 74
1

The numbers 255 and 100 in your first division are both int. So when you divide two ints in java you get the 'quotient'. Java then casts this answer to float.

You can instead cast your numerator to float before the division occurs to guarantee the result will be a float division.

Try:

public float NumberCalc(){
    float number1 = (float) 255/100;
    float number2 = (((float)5/366)*100);
    float finalNumber =(number1*number2);
    return finalNumber;
}
frogmanx
  • 2,620
  • 1
  • 18
  • 20
0

cast your fractions to a float or make variables set to (for example)

float a = 200f 

for your math. You don't need to make variables it just makes it neater in my opinion. Android calculates division into integers.

zgc7009
  • 3,371
  • 5
  • 22
  • 34