Bryan Bryan - 8 days ago 7
C# Question

How can I format a float number so that it looks like real time?

Update! I measure the time like this:
float delta = (float)gameTime.ElapsedGameTime.TotalSeconds;
time += delta;


I want to format a float number so that it looks like this:

minutes:seconds.milliseconds
"0:36.763"


Mario Kart picture

How can I do that?

Answer

Your question is vague one, providing that float contains seconds, e.g.

 float time = 156.763122f; // 2 minutes (120 seconds) and 36.763122 seconds

You can put (C# 6.0)

 string result = $"{(int)time / 60}:{time%60:00.000}";

Or

 string result = string.Format(CultureInfo.InvariantCulture,
   "{0}:{1:00.000}", (int)time / 60, time % 60);

A better approach, however, is to use TimeSpan which has been designed for that purpose:

 TimeSpan ts = TimeSpan.FromSeconds(time);

 String result = ts.ToString("m\\:ss\\.fff")