Reducing a float by 50%?

moveSpeed = (50 / 100) * 100;

doesnt seem to work

Do the maths in float too:

  • ensure moveSpeed is of type float
  • ensure numbers have f on the end, ie 50f / 100f

Else compiler may think you intend to work with integers.

Well first off - 50 divided by 100 times 100 is 50 again…

Secondly - you’re using integers instead of floats. If you want to reduce moveSpeed by half it’d be (assuming moveSpeed is a float)

moveSpeed *= 0.5f;
1 Like

The reason that doesn’t work is because the compiler sees all those numbers as integers, so it uses integer math. So, 50 / 100 becomes 0, multiplied by 100 becomes 0, and it’s only when it assigns that 0 to moveSpeed that it becomes a float.

You can just use 0.5f…

To clarify…

First, the given math doesn’t even reduce a value by 50%, so it’s really weird you would post it.
Second, the compiler sees that you do not specifically say that you want float values so it uses integers which it rounds down. Since 50/100 is 0.5f it rounds it down to zero, which makes multiplying it pointless.

So if you wanted to get 50 back again in your weird equation, just do this:

moveSpeed = (50f / 100f) * 100f;

But if you want to just reduce moveSpeed by half, do this:

moveSpeed = inputValues * 0.5f;
// or if it is already calculated...
finalMoveSpeed *= 0.5f;

I think you get the point.

yet another way

finalMoveSpeed = moveSpeed * 0.5f;
1 Like