How do I calculate and print the percentage increase/decrease between 2 numbers in Godot?

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

I’m building a little economic model for my game and I’d like for the player to be able to see his progress or regress in the form of percentage increase/decrease next to some economic indices on a yearly basis. For instance, let’s say oil output is 100 million tons for current year and for the next year is 120 million tons, how do I calculate and print the 20% percentage increase between those 2 numbers?

thanks in advance

:bust_in_silhouette: Reply From: jgodfrey

As a bare-bones example…

print("%s%%" % [((float(120000) / 100000) - 1) * 100])

That will print 20%.

Or, in the form of a function…

func calc_percentage(numerator: int, denominator: int) -> float:
	return ((float(numerator) / denominator) - 1) * 100

Call the above like:

var percentage = calc_percentage(120000, 100000)
print("%s%%" % percentage)

jgodfrey | 2022-12-12 20:30

can you explain, why here you’re subtracting 1 from the fraction of the numerator and denominator?

inxeoz | 2023-07-08 16:00

Because the request was to return 20% for the example given, which was:

120,000 / 100,000. That, by itself is 1.2. So, 120,000 is 1.2 times greater than 100,000 (or 20% greater, just written a different way). So, to get the 20% result, I needed to subtract out the 1 to leave only the 0.2 portion. Then, 0.2 x 100 = 20, which is format requested in the original post…

jgodfrey | 2023-07-08 18:53

thank you for your response I get it. now I can die peacefully

inxeoz | 2023-07-09 10:11