3

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
2
  • 2
    Also bear in mind that a TimeSpan always has a precision down to 100 nanoseconds. Just because you've rounded it, that doesn't mean that when you e.g. print it it won't (necessarily) still include some trailing 0s. (I mention this because of your mention of ts.ToString()) Dec 27, 2018 at 10:58
  • Possible duplicate of Can you round a .NET TimeSpan object? Dec 27, 2018 at 12:59

1 Answer 1

5

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));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.