+7 votes

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. : )


in Engine by (208 points)

1 Answer

+14 votes
Best answer

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.


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

Edit: Tried to make the answer more clear

by (492 points)
edited by

Thank you so much for this helpful answer. :D

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.

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

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.

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).

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

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 Frequently asked questions and 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 [email protected] with your username.