Chaos Project

RPG Maker => RPG Maker Scripts => Script Troubleshooting => Topic started by: Memor-X on May 19, 2013, 08:25:49 pm

Title: Percentage Calculation returns 0
Post by: Memor-X on May 19, 2013, 08:25:49 pm
i have this event set up with a Call Script


returner = (30/200)*100
p returner


every time it runs, it returns 0 despite the fact it should be returning 15, the purpose of this is supposed to return a percentage

so any know why this doesn't works? it works fine of i just stick 30 or 200 in the variable but the moment i divide them it becomes 0 (and from that, 0 x # will always equal 0)

Title: Re: Percentage Calculation returns 0
Post by: KK20 on May 19, 2013, 08:35:01 pm
The magical world of ints and floats.
Quote
(30/200)*100 = (0)*100 = 0

(30.0/200)*100 = (0.15)*100 = 15

(30/200.0)*100 = (0.15)*100 = 15
Title: Re: Percentage Calculation returns 0
Post by: Memor-X on May 19, 2013, 08:42:32 pm
make......sense, strange how a variable will detect the difference between 15 and "15" being an integer and string but not a float, added .to_f in my original code to the variables 30 and 200 represented and it works now, thanks
Title: Re: Percentage Calculation returns 0
Post by: KK20 on May 19, 2013, 08:47:35 pm
If you tagged a .0 to the end, then the variable will recognize it as a float. The simple act of dividing doesn't instantly make the program think "Oh, my user must want decimal numbers." I mean, you could rewrite the '/' method in Integer if you wanted to, but that would be plain stupid. :P
Title: Re: Percentage Calculation returns 0
Post by: Blizzard on May 20, 2013, 02:20:51 am
There is also something called a floating point precision error. Due to hardware limitations if you define 2.0, it may actually be 1.999999 and that prevision error propagates further during multiplication and summing. The alternative to avoid that and still have the proper result is to first do all multiplication operations.

Quote
30 * 100 / 200 = 3000 / 200 = 15


I personally avoid using floats whenever possible. Usually I use float only where the lack of precision isn't really a problem in the calculation.