FloatToInt and stuff [SOLVED]

Started by Atelier, Mon 04/07/2011 12:37:30

Previous topic - Next topic

Atelier

Hi, I'm working out a percentage of something and it works but doesn't seem very elegant:

Code: ags

float percentage = (IntToFloat(experience)/(IntToFloat(level)*1000.0))*100.0;
lbExp.Text = String.Format("%d%", FloatToInt(percentage, eRoundNearest));


Is there a simpler way without converting all these ints and floats?

Also, I'm having trouble with a slider..

Code: ags

// repeatedly_execute_always

expslider.Max = level*1000;           //level x 1000 is the experience to get in every level
expslider.Value = experience;         


if (level*1000 <= experience) {     //the player has enough experience to level up
   
   level++;
   int difference = level*1000 - experience;
   
   experience = 0 + difference;       //any surplus experience is carried on to the next level

}


If the player levels up more than once at a time (ie the difference is still bigger than level*1000), the expslider flickers back and forth while it's calculating it.

So is there a way to stop it updating the expslider until all the calculations are finished? (ie experience is finally less than level*1000). Thank you.

Gilbert

Haven't read the second part, but for the int-float part, since you're only going to use an integer result, you may try to simply the formula and see whether it can be done with only integer arithmetic.

The formula can be simplified as:
percentage = experience/(level*10)

The trick is, make sure that integer division operations are done at the very last moment (which already is the case in the above formula). So:
Code: ags

lbExp.Text = String.Format("%d%",experience/(level*10));

Note that since it now uses integer division, the result may deviate a tiny bit from what was done with floating point division and then have the result truncated.

Khris

For the second part: try replacing "if" by "while". Then in the case you described it should run twice before updating what the player sees.

Atelier

#3
Thanks you guys :D

monkey0506

Regarding the truncation Gilbot was talking about, I was just testing it recently and any integer division always rounds down. So even if the floating-point division resulted in, say 60.999% (rounded up to 61%), the integer division would return 60%. Probably not an issue in the long-run, but if it ever was you could use floating-point division for a more precise result.

Gilbert

Yeah, but even then, you can try to do the conversions as late as possible, only when it's necessary (i.e. a division is done):
Code: ags
lbExp.Text = String.Format("%d%",FloatToInt(IntToFloat(experience)/IntToFloat(level*10),eRoundNearest));

SMF spam blocked by CleanTalk