- Home /
Rounding Off A Float?
Hello,
I have a float (timer) that is basically Time.fixedTime. I use the timer for a GUI label. I want to have it so that the timer only uses the format: 0.0, so ... two digits.
How would one do that, in JavaScript?
Answer by Sydan · Sep 08, 2011 at 02:45 PM
http://answers.unity3d.com/questions/50391/how-to-round-a-float-to-2-dp.html
This may contain your answer. More shortly:
yourFloat = Mathf.Round(yourFloat * 10) / 10;
although you will probably need to use 10.0 rather than 10.
Thanks heaps for your answer, Thank god for grave digging :) Really helped thank you.
So simple... and yet so genius... You've saved me a lot of head scratching, thank you! And this also made me realise that I'm too dependant on methods, even on the simplest things. I'll work on changing that :p
But thanks again mate!
Answer by Bunny83 · Apr 14, 2020 at 02:33 AM
Since the question was already bumped I'd like to add that the solution that @Sydan proposed has several issues. First of all rounding the the value itself could significantly change how it changes over time. if you manually add deltaTime the rounding would essentially remove the change since it's so insignificantly small.
Not updating the original variable when performing the rounding would avoid the first issue. However the second issue will still stand. That is if the value gets larger it might not be possible to round to a nice 1 digit decimal place due to floating point precision. So occationally the float value could have more than 1 decimal digit also if the fractional part is 0 the ".0" usually disappears.
All those issues can be avoided by just using
string textToDisplay = yourFloat.ToString("F1");
This way you can keep your actual float value as it is. The standard format "F" just displays a floating point number. The "1" specifies the number of decimal places behind the decimal point. For more information see Standard Numeric Format Strings
Your answer
