Godot ignores decimal places in division - Why?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SawmillTurtle

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.

:bust_in_silhouette: Reply From: jgodfrey

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

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!

:slight_smile:

SawmillTurtle | 2020-02-26 23:32

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.

jgodfrey | 2020-02-27 00:12