0 votes

I'm attempting to set up a health bar manually by using simple percentages. The bar will be one hundred pixels long at most, and the actual length will be determined by the actual percentage of total health the player currently has. I have a function that looks like this:

var val: float;

func get_percent(a, b) -> float:
    val = a / b;
    val *= 10;
    val *= 10;
    return val;

So here's this code in a nutshell: the first line divides the health by the maxhealth. This should result in a zero with a decimal point. For example, 27 / 45 would equal 0.6. The next two lines each move the decimal one place to the right. In the aforementioned example, this would result in 60, which is the correct answer. 27 is 60% of 45. I could use this to draw a health bar 60 pixels long.

Now comes the issue: it doesn't work. When val divides the two numbers, it gets a zero with a decimal point and then discards the decimal point, so the result is always 0. 0 is not the right answer. 0 can't be used to do what I'm trying to do. I have tried everything imaginable to fix this. I even declared the variable as a float, so that Godot would KNOW that I indeed want the floating point. It did no good. Godot still tossed away the decimal point and gave me a 0.

Why is this? Why would it be programmed to do this? Is there any way to fix it? Please help me. This is really annoying.

in Engine by (44 points)

1 Answer

+3 votes
Best answer

It appears to be doing integer division, which is probably expected. Cast (at least) one of the values to a float:

var a = 27
var b = 45
print(a/b) # prints 0
print(float(a)/b) # prints 0.6
by (12,286 points)
selected by

I actually solved this just now by changing my function declaration as follows:

func get_percent(a: float, b: float) -> float:

I don't know why integer division is so particular, but there it is. Thanks for the help!


It's very typical (of programming languages in general) that an int divided by an int will result in an int. To ensure that you get floating point division, you need to promote at least one of the values to a float type.

Glad you have it working.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.