TimeSpan比较(毫秒精度)

tug*_*erk 4 c# time

我在这里碰到的东西很奇怪,但是我不确定是不是我知道TimeSpan API错误。打印出以下内容false,我不确定为什么:

var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(foo > bar);
Run Code Online (Sandbox Code Playgroud)

以下打印true

var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(foo == bar);
Run Code Online (Sandbox Code Playgroud)

进行比较时是否不TimeSpan.FromMilliseconds考虑毫秒精度?

das*_*ght 6

TimeSpan简单地舍入的毫秒数,你通过它,这样既123.33123.34最终代表123毫秒的时间跨度。123.5将四舍五入到123毫秒。

如果您需要更高的精度,请自己打勾:

var foo = TimeSpan.FromTicks((long)(123.34*TimeSpan.TicksPerMillisecond));
var bar = TimeSpan.FromTicks((long)(123.33*TimeSpan.TicksPerMillisecond));
Console.WriteLine(foo > bar);
Run Code Online (Sandbox Code Playgroud)

现在,您的程序产生了Truedemo)。