Percentages / floating point HOWTO?

Ask and answer questions about making games and related topics. Unrelated topics go in that other forum.

Moderators: marionline, SDHawk

Post Reply
LieMurderProfit
Slime
Posts: 20
Joined: Mon Feb 13, 2017 10:28 am
Location: Moscow

Percentages / floating point HOWTO?

Post by LieMurderProfit »

Does anyone know of any scripts/hacks to do percentages?

I'm trying to find the percentage of rotten apples in a barrel.

200 apples
10 are bad

percentage: (10/200) x 100 = 5%

The result in Hamster is 0, I guess because I'm using integers.

A side note: When searching the wiki I noticed an example that returns a zero value if the max stat is less than 100.
http://rpg.hamsterrepublic.com/ohrrpgce ... ripting%3F

I'm not looking forward to writing a huge long division script :hurr:
Wendigo
Red Slime
Posts: 52
Joined: Tue Feb 28, 2017 1:15 pm

Post by Wendigo »

You can circumvent the integer issue by adjusting the formula

Code: Select all

percentage: (10/200) x 100 = 5%
is the same as
percentage: (10 x 100) / 200 = 5%
if you need the part behind the decimal point you could multiply by 100 to get two decimal places.
Example:

Code: Select all

percentage: (10 x 100) / 200 = 5[,00000]
...
percentage: (10 x 100 x 100) / 200 = 5[00]
So you could treat the last two digits as decimal places.
If you convert it into a string put a decimal point in front of the last two digits.
Last edited by Wendigo on Mon Mar 13, 2017 10:17 am, edited 1 time in total.
TMC
Metal King Slime
Posts: 4308
Joined: Sun Apr 10, 2011 9:19 am

Post by TMC »

Thanks, that was a pretty major error on that wiki page! I've fixed it.

You can nearly always work around the lack of floating point by scaling everything up by a constant factor or by being careful of the order in which you perform operations.

For example, in the Sidescroller 101 scripts, positions and velocities are measured in tenths of a pixel everywhere. They're only converted to pixels at the last moment when calling "put hero".
Last edited by TMC on Mon Mar 13, 2017 4:05 pm, edited 1 time in total.
LieMurderProfit
Slime
Posts: 20
Joined: Mon Feb 13, 2017 10:28 am
Location: Moscow

Post by LieMurderProfit »

wow Wendigo, that was a lot simpler than I had imagined, and accurate enough for my use. thanks.

Thanks for the pointer TMC.
Post Reply