Rounding to 2 decimal places?

I have a timer and I’ve attached this script to it :

var TimeTaken : float;

function Update () {
TimeTaken = Time.time;
TimeTaken = Mathf.Round(TimeTaken);
}

I want it rounded to 2 decimal places but all I’m getting is the whole number instead of decimals. How can i round TimeTaken to 2 decimal places?

I tried TimeTaken = Mathf.Round(TimeTaken/100); and the timer completely froze. :neutral:

I’d appreciate any help.

var result = (Mathf.Round(TimeTaken * 100)) / 100.0

4 Likes

Perfect! It works great now. Thanks.:smile:

What are you doing this for?

If you’re using it to display the timer in your GUI then you can request a format as you convert it to a string - something like “number.ToString(”#.00")" should get what you want. Note that ToString() is implicitly called when you try to use anything that’s not a string as a string.

5 Likes

Thanks for the advice.

1 Like

Using System;

roundValue = Math.Round( notRoundValue, 2);

Or better yet, to get commonly expected results:

roundValue = Math.Round( notRoundValue, 2, MidpointRounding.AwayFromZero);

The default rounds towards the Even value, which can be a surprise.

5 Likes

5 years later, but still helped me answer such simple question with such simple line of code. Thanks!

5 Likes

THANK YOU SO MUCH

Always a good one to google :smile:

It works perfectly! Thank you!

text = $"{someFloat:#0.00}";

Intellisense gave me this suggestion when using interpolated strings (aka using the $-sign). Super neat!