Search code examples
c#timertimespanmilliseconds

c# How to truncate milliseconds with timespan?


I want to display a float that represents the timer and I am trying to format it like this:

00:00:00 (Minutes:Seconds:Milliseconds)

public static string ConvertToTime(float t){
    TimeSpan ts = TimeSpan.FromSeconds(t);

    return string.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds);
}

But this will give the full milliseconds, not a precision less even I defined the format with 00.

For example if the timer is 3.4234063f it should output 00:03:42 not 00:03:423.

Its such a basic thing, but I can't resolve it when using timespan.


Solution

  • In the interests of your users' sanity, I recommend that you display the time as mm:ss.ss where you display the seconds to two decimal places.

    To do so:

    public static string ConvertToTime(float t)
    {
        return string.Format("{0:00}:{1:00.00}", t/60, t%60);
    }