Float precision after mathematical operations and Display %f **SOLVED**

Started by Knox, Tue 01/06/2010 23:07:10

Previous topic - Next topic

Knox

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:
Code: ags

float playerHealth = 18.0;
float playerHealthPercent = 100.0;

In a custom function:
Code: ags

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

When player is clicked on:
Code: ags

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% ?
--All that is necessary for evil to triumph is for good men to do nothing.

Khris

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.)

Code: ags
  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().

Gord10

Display("%% %.2f",f); should solve it. %.Xf means X digits are shown as the floating number.
Games are art!
My horror game, Self

Knox

aw shucks guys I missed that in the manual...:-[

Ok Im going to see what I can do with it, thanks!
--All that is necessary for evil to triumph is for good men to do nothing.

SMF spam blocked by CleanTalk