Millisecond accurate TimeSpan comparison

I find something here, which is very strange, but I'm not sure if it is 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);

Does the TimeSpan.FromMillisecondsaccuracy of milliseconds take into account when performing the comparison?

+4
source share
4 answers

TimeSpanjust rounding the number of milliseconds that you pass, so the two 123.33and 123.34end up representing the time interval of 123 milliseconds. 123.5will be rounded to 123 milliseconds.

If you need higher accuracy, do the math with ticks yourself:

var foo = TimeSpan.FromTicks((long)(123.34*TimeSpan.TicksPerMillisecond));
var bar = TimeSpan.FromTicks((long)(123.33*TimeSpan.TicksPerMillisecond));
Console.WriteLine(foo > bar);

True ().

+4

API http://msdn.microsoft.com/en-us/library/system.timespan.frommilliseconds(v=vs.110).aspx TimeSpan.FromMilliSeconds(double d) , , double , TimeSpan.

, TimeSpan. . , - OverflowException , , MinValue MaxValue.

:

GenTimeSpanFromMillisec (1);
        GenTimeSpanFromMillisec (1.5);
        GenTimeSpanFromMillisec (12345.6);
        GenTimeSpanFromMillisec (123456789.8);
        GenTimeSpanFromMillisec (1234567898765.4);
        GenTimeSpanFromMillisec (1000);
        GenTimeSpanFromMillisec (60000);
        GenTimeSpanFromMillisec (3600000);
        GenTimeSpanFromMillisec (86400000);
        GenTimeSpanFromMillisec (1801220200),

+1

Timespan , .

, timespan ; .

0
source

His problem with accuracy:

var fooba = TimeSpan.FromMilliseconds(123.36d);
var foob = TimeSpan.FromMilliseconds(123.35d);
var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(fooba + " > " + foob + "?: " + (fooba > foob));
Console.WriteLine(foob + " > " + foo + "?: " + (foob > foo));
Console.WriteLine(foo + " > " + bar + "?: " + (foo > bar));
Console.WriteLine(fooba + " == " + foob + "?: " + (fooba == foob));
Console.WriteLine(foob + " == " + foo + "?: " + (foob == foo));
Console.WriteLine(foo + " == " + bar + "?: " + (foo == bar));

00:00:00.1230000 > 00:00:00.1230000?: False
00:00:00.1230000 > 00:00:00.1230000?: False
00:00:00.1230000 > 00:00:00.1230000?: False
00:00:00.1230000 == 00:00:00.1230000?: True
00:00:00.1230000 == 00:00:00.1230000?: True
00:00:00.1230000 == 00:00:00.1230000?: True
0
source

All Articles