Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan rounds off to 3 decimal positions

Tags:

c#

.net

timespan

For the below line :

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

i expect sec = 0.0008 , but it gets rounded of to 3 decimal positions and gives result as 0.001 , any workarounds.

like image 971
Keshav Raghav Avatar asked Jan 25 '23 03:01

Keshav Raghav


1 Answers

As per the docs, FromMilliseconds rounds to the nearest millisecond:

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

Note the docs are correct only for .NET Framework. .NET Core 3.x will work as the OP was hoping for (returns 0.0008, contrary to the docs).

If you want this to work in .NET 4.x - consider multiplying the milliseconds by 10,000 (TicksPerMillisecond) and then call FromTicks (or the constructor) rather than 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 .

like image 176
mjwills Avatar answered Jan 29 '23 07:01

mjwills