Home > OS >  Unity timer with 2 digit milliseconds
Unity timer with 2 digit milliseconds

Time:01-09

I have got a timer that works, but I would like it to be formatted like this:

0:00:00

instead of this

0:00:000


public class Timer : MonoBehaviour
{
    public float timeValue = 0;
    public TextMeshProUGUI TimeText;

    private void Update()
    {
        timeValue  = Time.deltaTime;
        DisplayTime(timeValue);
    }

    private void DisplayTime(float timeToDisplay)
    {
        float Minutes = Mathf.FloorToInt(timeToDisplay /60);
        float Seconds = Mathf.FloorToInt(timeToDisplay % 60);
        float MilleSeconds = timeToDisplay % 1 * 1000;

        TimeText.text = string.Format("{0:0}:{1:00}:{2:00}" , Minutes , Seconds, MilleSeconds);
    }
}

I tried to change the format in code from this

{0:0}:{1:00}:{2:000}

to this

{0:0}:{1:00}:{2:00}

but it didn't change anything.

Please help

CodePudding user response:

Issue will be you probably want the 2 significant digits

but in general the milliseconds are e.g. 002 with ToString("00") this will will become 02 wich is wrong.

Also e.g. 123 will just stay 123 as the custom formatter 00 only comes into play when there are insignificant digits (in your case leading 0).

=> I would either go with Substring instead and shorten it to a max length of 2 while using 000 as format to be sure there is always all three digits included

See demo

Or alternately why not just use and stick to the seconds only and do

float Minutes = Mathf.FloorToInt(timeToDisplay /60);
timeToDisplay -= Minutes * 60;
var secondsDisplay = timeToDisplay.ToString("00.00").Replace('.', ':');

TimeText.text = $("{Minutes:0}:{secondsDisplay}");

which would do the rounding for you as well

CodePudding user response:

Using a little maths and casting to int you can grab the components of the given time value.

private void DisplayTime(float timeToDisplay)
{
    // get the total full seconds.
    var t0 = (int) timeToDisplay;

    // get the number of minutes.
    var m = t0/60;

    // get the remaining seconds.
    var s = (t0 - m*60);

    // get the 2 most significant values of the milliseconds.
    var ms = (int)( (timeToDisplay - t0)*100);

    TimeText.text = $"{m:00}:{s:00}:{ms:00}";
}

This way you don’t need more strings created than required, especially if this is performed many times a second. And you’re not performing any remainder calculations (%), which are often frowned upon.

The code can be trivially extended to include hours (by dividing t0 by 3600), but that doesn’t seem to be a requirement.

  • Related