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
marsze
  • 15,079
  • 5
  • 45
  • 61
  • 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()`) – Damien_The_Unbeliever Dec 27 '18 at 10:58
  • Possible duplicate of [Can you round a .NET TimeSpan object?](https://stackoverflow.com/questions/338658/can-you-round-a-net-timespan-object) – Marcell Toth Dec 27 '18 at 12:59

1 Answers1

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));
marsze
  • 15,079
  • 5
  • 45
  • 61