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?

This may contain your answer. More shortly:

yourFloat = Mathf.Round(yourFloat * 10) / 10;

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