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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With