Problem when float is rounded up [SOLVED]

I’m generating a float and using it in 2 ways.

  1. Using the float to test a condition.
  2. Displaying the float to the player, rounded to 3 decimal places.

The problem is that when I round to 3 decimal places, the 3rd digit is rounded up (if the 4th is 5 or higher) which can lead to an incorrect outcome.

Here’s my script:

theFloat = Time.time; // gives a number to 7 decimal places
if (theFloat < 0.500000) {
	//do something
}
guiTextObject.text = theFloat.ToString("0.000"); //only display 3 decimal places

In that example, if theFloat happens come up something like 0.4999998 then the test in the if statement will be true but the display to the player will be 0.500 instead of 0.499 since it gets auto rounded up. You see, in this game .499 is bad and 0.500 is good.

Is there a way to round theFloat to 3 decimals before I check the number so that I’m testing with exactly the same number that I’m displaying? Or is there a way to round off a float without it automatically rounding itself up?

This may help you out: http://forum.unity3d.com/viewtopic.php?t=8130&highlight=mathf+round

-Raiden

Cool! Weird that I didn’t find that thread during my search.

Their solution still isn’t working exactly as I need.

	reactionTime = Time.time;
	roundedRT = Mathf.Round(reactionTime * 1000) / 1000;
	Debug.Log(roundedRT);
	Debug.Log(reactionTime);

I’m trying to round to 3 decimal places eg. 0.469. But for some reason when I round to 3 places with the above code, I get back 2 places like 0.47. It seems to be always making the 3rd digit a zero which I do not want.

Cancel that, looks like Mathf.Floor does what I was looking for.

roundedRT = Mathf.Floor(reactionTime * 1000) / 1000;

Another question tho: Is there a way to display the zero when it comes up in the 3rd decimal place? So instead of 0.49 you’d see 0.490?

I haven’t found a way to do it mathematically. I have some timer code I wrote that I needed to display zero’s, and I ended up using logic and a string to set the zero, so it showed that way in the display text.

-Raiden

You can display the trailing zero using the magic string.Format function:-

Debug.Log(string.Format("{0:f3}", .34f));

Look in the Mono docs to see exactly how string.Format works. Essentially, though, it’s a bit like a souped-up version of the printf function from the C standard library. You specify a string with placeholders in it (the curly braces and their contents). The first number (0 in this case) determines which of the remaining parameters will replace that placeholder. After this number, you can optionally have a format specifier after a colon. In this case, the “f3” means “floating point format, three decimal places”.

Works perfectly! Thanks andeeee! Here’s how I used it:

reactionTime = Time.time;
roundedRT = Mathf.Floor(reactionTime * 1000) / 1000;
formatedRT = String.Format("{0:f3}", roundedRT);
rtText.text = formatedRT.ToString();
Debug.Log(reactionTime);