Reputation: 197
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"
How can I do that?
Upvotes: 3
Views: 2941
Reputation: 186813
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")
Upvotes: 2
Reputation: 85
Your question is referring to TimeSpan formatting. If these answers aren't sufficient, you'll find plenty of information using that keyword. I've typically used the following approach.
float time = 75.405f;
TimeSpan TimeInSeconds = TimeSpan.FromSeconds(time);
string StringTime = TimeInSeconds.ToString(@"m\:ss\.fff");
Console.WriteLine(StringTime);
The output of which is
1:15.405
You'll likely want to store your game timer in float seconds. You can convert that to a TimeSpan by specifying from which format you're using (seconds). After that, you can simply convert using the TimeSpan's ToString()
method with the correct format specifiers. More information can be found here.
https://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx
By the way, I noticed you've tagged your question as XNA. While XNA is fantastic by all measures, keep in mind that XNA is depreciated and you may want to consider porting to MonoGame or SFML.NET.
Upvotes: 0
Reputation: 109762
You are using a time span, so you can use a TimeSpan
object and make use of its custom formatting:
var timeSpan = TimeSpan.FromSeconds(36.763);
Console.WriteLine(timeSpan.ToString("m\\:ss\\.fff"));
This outputs: 0:36.763
The m
specifier denotes single digit minutes, ss
denotes double digit secnds and .fff
denotes three decimal places of milliseconds.
The \\:
is an escape sequence for :
and \\.
is an escape sequence for .
.
You could also write the custom format string as @"m\:ss\.fff"
You can also specify days, hours, minutes, seconds and milliseconds separately if you happen to have the interval represented that way:
var timeSpan = new TimeSpan(0, 0, 0, 36, 763); // (days, hours, mins, secs, ms)
Upvotes: 1