Ian094
November 17, 2013, 10:11pm
1
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
Ian094
November 17, 2013, 10:32pm
3
Perfect! It works great now. Thanks.
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
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
angrypenguin:
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 years later, but still helped me answer such simple question with such simple line of code. Thanks!
5 Likes
Always a good one to google
nyirkos
September 7, 2022, 5:17pm
11
angrypenguin:
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.
It works perfectly! Thank you!
text = $"{someFloat:#0.00}";
Intellisense gave me this suggestion when using interpolated strings (aka using the $-sign). Super neat!