Marcio Miitooo
Marcio Miitooo

Reputation: 31

How to round a TimeSpan to one digit for millisecond

How I can round to get only one digit for milliseconds?

I tried some solution from this link but no one works: Can you round a .NET TimeSpan object?

00:23:01.4999890 -> 00:23:01.5
15:02:02.9999785 -> 15:02:03.0
08:03:59.9605388 -> 08:04:00.0
03:16:00.8605388 -> 03:16:00.9
19:12:01.8420745 -> 19:12:01.8
04:05:03.8417271 -> 04:05:03:8

Upvotes: 3

Views: 3018

Answers (1)

marsze
marsze

Reputation: 17035

You could round to 100 milliseconds (10ths of a second) like this:

var timespan = TimeSpan.Parse("00:23:01.4999890");
var rounded = TimeSpan.FromSeconds(Math.Round(timespan.TotalSeconds, 1));

Then use a custom format string to display only 1 digit after the decimal point:

rounded.ToString(@"hh\:mm\:ss\.f");
// OUTPUT:
// 00:23:01.5

Another option would be using the extension method from this answer:

rounded = timespan.Round(TimeSpan.FromMilliseconds(100));

Upvotes: 5

Related Questions