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?
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.
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.
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”.