TimeSpan 四舍五入到小数点后 3 位

TimeSpan rounds off to 3 decimal positions

对于以下行:

decimal sec = (decimal)TimeSpan.FromMilliseconds(.8).TotalSeconds;

我预计 sec = 0.0008 ,但它四舍五入到小数点后 3 位,结果为 0.001 ,任何解决方法。

根据 the docsFromMilliseconds 四舍五入到最接近的毫秒数:

Therefore, value will only be considered accurate to the nearest millisecond.

请注意,文档仅适用于 .NET Framework。 .NET Core 3.x 将像 OP 希望的那样工作(returns 0.0008,与文档相反)。

如果您希望它在 .NET 中工作 4.x - 考虑将毫秒数乘以 10,000 (TicksPerMillisecond),然后调用 FromTicks(或构造函数)而不是 FromMilliseconds:

using System;

public class Program
{
    public static void Main()
    {
        var ticksPerMillisecond = TimeSpan.TicksPerMillisecond;
        decimal sec = (decimal)TimeSpan.FromMilliseconds(.8).TotalSeconds;
        decimal sec2 = (decimal)TimeSpan.FromTicks((long)(0.8 * ticksPerMillisecond)).TotalSeconds;
        decimal sec3 = (decimal)new TimeSpan((long)(0.8 * ticksPerMillisecond)).TotalSeconds;

        Console.WriteLine(sec);  
        // 0.0008  .NET Core 
        // 0.001   .NET Framework
        Console.WriteLine(sec2);
        // 0.0008  .NET Core
        // 0.0008  .NET Framework 
        Console.WriteLine(sec3);
        // 0.0008  .NET Core
        // 0.0008  .NET Framework

    }
}

This blog post has further reading on the issue. Fiddle available at https://dotnetfiddle.net/YfIFjQ .