I'm hitting something here which is very odd but I'm not sure whether it's me knowing the TimeSpan APIs wrong. The following prints out false
and I'm not sure why:
var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(foo > bar);
The following prints true
:
var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(foo == bar);
Doesn't TimeSpan.FromMilliseconds
take millisecond precision into account while doing the comparison?
Its an issue with precision:
TimeSpan
simply rounds the number of milliseconds that you pass it, so both123.33
and123.34
end up representing a timespan of 123 milliseconds.123.5
would be rounded up to 123 milliseconds.If you need better precision, do the math with the ticks yourself:
Now your program produces
True
(demo).Timespan accepts a floating point as a parameter for milliseconds but ignores the decimals.
Makes sense, as timespan has no notion of sub-milliseconds; it's the smallest unit.
According to the API documentation http://msdn.microsoft.com/en-us/library/system.timespan.frommilliseconds(v=vs.110).aspx the method
TimeSpan.FromMilliSeconds(double d)
takes any double value but only respects values up to one digit after the comma since the double is converted into ticks before it is used within the TimeSpan struct.This is also emphasized by the examples on that site: