简体   繁体   中英

Should I worry about losing precision with this DateTime math?

This code:

if (dt.Subtract(prevDt).TotalMinutes == 15)

("dt" and "prevDt" are DateTime vars that contain values such as "7/20/2012 7:30:00 AM" and "7/20/2012 7:45:00 AM")

...causes ReSharper to warn me with:

"Comparison of floating point numbers with equality operator. Possible loss of precision while rounding values."

Is this a valid warning, and if so, how would I appease it? I wish ReSharper were a little more like Eclipse, which offers to fix things it complains about.

At any rate, the code seems to work fine, although I'd rather not have it stink up the joint if this is a code smell.

If you are sure that your timestamps are exactly on 15 minute boundaries and not a few milliseconds off, then your code will work fine. Values that can be represented exactly as an int can also be represented exactly as a double.

If you want to try to rewrite your code to avoid the warning, you might want to try this:

if (prevDt.AddMinutes(15) == dt)

不,如果您的日期总是相隔15分钟,则不是有效警告,否则没有秒或毫秒(或滴答)的差异。

You may use Minutes with all other properties (Days/Hours...) to compare TimeSpans for portions you care about (ie ignore seconds).

Otherwise it may be better to check if TotalMinutes not too far off instead of exact match if your values are ever could contain seconds/milliseconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM