TimeSpan 与毫秒精度的比较 [英] TimeSpan comparison with millisecond precision

查看:66
本文介绍了TimeSpan 与毫秒精度的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到了一些很奇怪的事情,但我不确定是不是我知道 TimeSpan API 错误.以下打印出 false,我不知道为什么:

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);

以下打印true:

var foo = TimeSpan.FromMilliseconds(123.34d);
var bar = TimeSpan.FromMilliseconds(123.33d);
Console.WriteLine(foo == bar);

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

Doesn't TimeSpan.FromMilliseconds take millisecond precision into account while doing the comparison?

推荐答案

TimeSpan 只是四舍五入你传递的毫秒数,所以 123.33123.34 最终代表 123 毫秒的时间跨度.123.5 将四舍五入为 123 毫秒.

TimeSpan simply rounds the number of milliseconds that you pass it, so both 123.33 and 123.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:

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

现在您的程序生成 True(demo).

Now your program produces True (demo).

这篇关于TimeSpan 与毫秒精度的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆