Why does calculating a percentage produce the number zero if it isnt the 100%

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

Hello Im not very good at maths, what I am trying to do it make the players health always be in percentage so I can change the health in the background but make it only show a percentage of 100, I found online a small java script that had this line in it
(current health / max health) * 100 # from what I can tell this should give me a percentage everytime, I tried this on a calculator doing 60 / 120 * 100 gave me 50 percent which is correct but in godot it produces just zero if it isnt 120 / 120 * 100 which gives me 100%

here is the pasteall Link that leads to my code:

Okay I think I figured it out, it seems to be because the var´s arent floats and for what ever reason (Im not good at math) if its a int it produces zeros but if its a float it produces the percentage of course it has decimals so I just convert it back into a int and there it is the percentage I wanted!

Dragon20C | 2020-11-04 07:47

You may use that function as helper :slight_smile:

func calcPercentage(partialValue, totalValue):
  return int((float(partialValue) / totalValue) * 100)

kuzey | 2022-10-15 08:01

:bust_in_silhouette: Reply From: larrxi

Cast one of the values to float before division.
Also round it before casting to int for a smoother convert to int.

print(str(int(round((float(current_health) / player_health) * 100))))