One Decimal Place [SOLVED]

Started by Atelier, Mon 27/05/2013 14:26:14

Previous topic - Next topic

Atelier

Hi, a very simple question, how would I display a float in a label so that it only shows it to 1 DP, with nearest rounding?

At the moment it shows it to 3+ DPs, depending on the width of the label.

Khris

The short answer is
Code: ags
  label.Text = String.Format("%.1f", value);

This might not do proper rounding though, just cut off the value.

If it doesn't, try
Code: ags
  label.Text = String.Format("%f", IntToFloat(FloatToInt(value * 10.0, eRoundNearest)) / 10.0);

Atelier

I tried something like snippet 2 to begin with but it doesn't seem to work - you either get a string of 9s or 0s after the 1st DP.

The first line is great though, I'm losing precision anyway when I chop off the rest, so it doesn't matter too much about perfect rounding :)

Thanks Khris!

Crimson Wizard

Quote from: Atelier on Mon 27/05/2013 14:49:10
I tried something like snippet 2 to begin with but it doesn't seem to work - you either get a string of 9s or 0s after the 1st DP.
Well, you could combine both rounding and cutting?

Snarky

You mean like this, CW?

Code: ags
  label.Text = String.Format("%.1f", IntToFloat(FloatToInt(value * 10.0, eRoundNearest)) / 10.0);


You could also go with:

Code: AGS

  int integerPart = FloatToInt(value, eRoundNearest);
  int decimalPart = FloatToInt(value*10.0, eRoundNearest) - integerPart*10;
  label.Text = String.Format("%d.%d", integerPart, decimalPart);


But this might all be sort of pointless; do we have any reason to think the standard "%.1f" formatting doesn't round correctly?

Crimson Wizard

Quote from: Snarky on Mon 27/05/2013 16:18:09
But this might all be sort of pointless; do we have any reason to think the standard "%.1f" formatting doesn't round correctly?
Hmm.... actually it does :).
Something I forgot.

SMF spam blocked by CleanTalk