Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: Knox on Tue 01/06/2010 23:07:10

Title: Float precision after mathematical operations and Display %f **SOLVED**
Post by: Knox on Tue 01/06/2010 23:07:10
Hi,

I just want to be able to display a player's health in percentage using floats. I tried with int's at first hoping (somehow!) it would convert automatically to a 1 decimal float...anyways, I tried this by placing 1 decimal for my initial floats:

Declared at top of global script:

float playerHealth = 18.0;
float playerHealthPercent = 100.0;

In a custom function:

function playerModifyHealth(float fHealthAmount)
{
 playerHealth = (playerHealth + fHealthAmount);
 playerHealthPercent = ((playerHealth/18.0)*100.0);
}

When player is clicked on:

cEgo.Say("My health is %f percent", playerHealthPercent)


However, the float percentage gets displayed with 6 decimal points...I thought of "truncate" but it seems to be for strings only. Is there a way outside of using a module or converting the numbers to strings to truncate the 6 decimal precision on floats to 1 decimal, as in...95.5%, or 1.5%...?

If not, is there a way to round off the float to the nearest number so that 93.4% would give me 93% ?
Title: Re: Float precision after mathematical operations and Display %f
Post by: Khris on Tue 01/06/2010 23:19:39
It doesn't matter how many decimals the initial float value has.
The string formatting code for a one decimal float is
  %.1f
(The manual entry on Display has a link to the string formatting section (http://www.adventuregamestudio.co.uk/manual/StringFormats.htm).)

 cEgo.Say("My health is %.1f%%", playerHealthPercent);

In theory you could use Truncate, but only after converting the float to a String (using String.Format).

Edit: Btw, rounding floats is done using FloatToInt() (http://www.adventuregamestudio.co.uk/manual/FloatToInt.htm).
Title: Re: Float precision after mathematical operations and Display %f
Post by: Gord10 on Tue 01/06/2010 23:23:28
Display("%% %.2f",f); should solve it. %.Xf means X digits are shown as the floating number.
Title: Re: Float precision after mathematical operations and Display %f
Post by: Knox on Wed 02/06/2010 00:14:45
aw shucks guys I missed that in the manual...:-[

Ok Im going to see what I can do with it, thanks!