1/4 = 0, not .25 (Why isn't Division working in GDScript?)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Corruptinator
:warning: Old Version Published before Godot 3 was released.

Hello! I’m not sure this is either a bug or not but what is happening is that I was trying to configure a meter bar to make it reach to maximum limit by dividing the number limit by the current input number such as this:

[Current Number] / [Maximum Limit]

Instead, all I got was 0 as a result.

Please check the GDscript by using the Print function and see if the results equals 0. like this.

1/4 = ?
2/40 = ?
3/4 = ?

If this is a bug in the GDScript, please let me know… Otherwise if there is an alternative way of dividing a number by a higher number then I like to know that too. : )

Thanks!

:bust_in_silhouette: Reply From: atze

That’s the way math works in programming (C, C++, Java, Python, and lots more). It’s called integer division. If you divide two integers, you always get an integer.
What you want is floating point division. To get that, you have to make sure that at least one of the numbers is a floating point number.

Example

var n1 = 1
var n2 = 4
float(n1)/2 # = 0.25

Edit: Tried to make the answer more clear

Thank you so much for this helpful answer. :smiley:

I’m sure there will be others who might get confused to why doing divisions in the opposite doesn’t work in programming, but hopefully the best answer will help resolve such minor to major issues.

Corruptinator | 2016-05-28 08:51

Also, how you declare a variable changes things. e.g.

var a = 1.0
var b = 4.0
print( a/b)

will print 0.25. The above variables are floating point whereas

var a = 1
var b = 2
print(a/b)

are integers and this will print 0.

If I were you I’d read up on handling floating point numbers in general. It’s not just division that will trip you up.

duke_meister | 2016-05-28 09:46

Quick note – 1.0/2 as well as 1/2.0 will both produce 0.5 as a float (as long as one of them is a float, the result is float as well).

Bojidar Marinov | 2016-05-28 12:51

Thanks, i was creating a healthbar that draws the width of the green part by 480*netHealth (net stands for neutralized)
where the netHealth is the health/maxHealth
but after the first hit the netHealth became 0
it was because of the integer division.
Thank you, you helped me a lot

PugMasterPug | 2017-08-15 16:30