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

How to round a TimeSpan to one digit for millisecond

如何四舍五入以在毫秒内只得到一位数字?

我从这个 link 尝试了一些解决方案,但没有一个有效: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

您可以像这样四舍五入到 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));