如何将TimeSpan舍入为一位数毫秒

时间:2018-12-27 03:52:15

标签: c# .net math rounding timespan

我如何舍入仅获得一位数字(毫秒)?

我尝试了此链接的一些解决方案,但没有一个起作用: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

1 个答案:

答案 0 :(得分:3)

您可以这样舍入到100毫秒(十分之一秒):

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

然后使用custom format string在小数点后仅显示一位数字:

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

另一种选择是使用this answer中的扩展方法:

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