Why does TimeSpan.FromSeconds(double) round to milliseconds?

前端 未结 5 1940
悲哀的现实
悲哀的现实 2020-12-15 03:22

TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

5条回答
  •  我在风中等你
    2020-12-15 04:08

    FromSeconds uses private method Interval

    public static TimeSpan FromSeconds(double value)
    {
        return Interval(value, 0x3e8);
    }
    

    0x3e8 == 1000

    Interval method multiplay value on that const and then cast to long (see last row):

    private static TimeSpan Interval(double value, int scale)
    {
        if (double.IsNaN(value))
        {
            throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN"));
        }
        double num = value * scale; // Multiply!!!!
        double num2 = num + ((value >= 0.0) ? 0.5 : -0.5);
        if ((num2 > 922337203685477) || (num2 < -922337203685477))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
        }
        return new TimeSpan(((long) num2) * 0x2710L); // Cast to long!!!
    }
    

    As result we have precision with 3 (x1000) signs. Use reflector to investigate

提交回复
热议问题