-3

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.

Mc Midas
  • 189
  • 1
  • 5
  • 17
  • 1
    I don't understand your question. Please edit your question with an example of what you want. Exactly. – Grantly Mar 14 '18 at 14:57
  • 1
    I don't understand either. If you have, say, 750ms in the MS part of the timespan, how do you expect to display that in two digits? – Matthew Watson Mar 14 '18 at 14:58
  • 2
    By definition there are 1000 milliseconds in a second - i.e milliseconds are thousandths of a second... if you only want to display 2 digits, you're looking for hundredths of a second, not thousandths... so `ts.Milliseconds / 10` – Diado Mar 14 '18 at 15:00
  • 1
    Why are you even using a `Timespan`? You just want the fractional part of a float and the integer part mod 60 and the integer part div 60. And don't use a colon when you mean the decimal part, use a period otherwise you will confuse whoever looks at this code next. "00:00.00" – Ian Mercer Mar 14 '18 at 15:03
  • What if you take the first two characters of the ms string? ts.Milliseconds.ToString().Substring(0,2) – Zukki Mar 14 '18 at 15:04
  • 1
    What you seem to want is centiseconds, not milliseconds – juharr Mar 14 '18 at 15:07
  • `423` milliseconds is not `42` milliseconds. You want an incorrect result. – Tim Schmelter Mar 14 '18 at 15:08
  • @TimSchmelter I know this but i dont want the last number. Anyways I fixed it using ts.Milliseconds * 0.1f – Mc Midas Mar 14 '18 at 15:13
  • @Zukki this works but will concat a new string. – Mc Midas Mar 14 '18 at 15:14

2 Answers2

0

Don't use a TimeSpan when all you need is some simple math.

Something like this (untested) avoids the allocation and accomplishes what you want.

public static string ConvertToTime(float t){
    int totalSeconds = (int)t;
    int minutes = totalSeconds / 60;
    int seconds = totalSeconds % 60;
    int hundredthsOfASecond = (int)((t - totalSeconds)*100);
    return $"{minutes:00}:{seconds:00}.{hundredthsofASecond:00}";
}
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
0

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);
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276