Bryan Bryan - 1 year ago 98
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:


Mario Kart picture

How can I do that?

Answer Source

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}";


 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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download