0

I was coding today, when I occurred this problem.

System.out.println(block.chance); // -> 10
float chanceFloat = block.chance / 100;
System.out.println(chanceFloat); // -> 0.0

I'm not sure what is the problem.

Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
Raikas
  • 11
  • 2
    I guess `block.chance` is an `int`. If so, I'd suggest you read [Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0) – QBrute Feb 07 '20 at 14:05
  • 1
    Let me guess: `block.chance` is an integer? try `float chanceFloat = block.chance / 100f;` – SteffenJacobs Feb 07 '20 at 14:05

2 Answers2

1

You are not stupid, you just are not aware of the language rules.

block.chance seems to be an integer, and the result of a division of two integers is an integer, even if it is assigned to a float cariable afterwards (then it is too late).

Your solution would be to use one of

float chanceFloat = block.chance / 100.0;
float chanceFloat = block.chance / 100.0f;
float chanceFloat = block.chance / 100.f;
float chanceFloat = block.chance / 100f;
float chanceFloat = (float)block.chance / 100;
glglgl
  • 81,640
  • 11
  • 130
  • 202
0

If block.chance is an integer, then block.chance/100 will be performed as integer division (i.e., the result is truncated), and then cast to a float.

If block.chance is positive and less than 100, this will always be 0.

The simplest fix is to ensure that the divisions requires floating point numbers by changing the type of at least one side of the division. The common idiom would be

float result = block.chance / 100.0;
D. Ben Knoble
  • 3,649
  • 1
  • 18
  • 31