Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AddMilliseconds round the double parameter?

DateTime.Now.AddMilliseconds(1.5); // adds 2 milliseconds

What on earth were they thinking here? It strikes me as horrendously bad practice to create a method that takes a double if it doesn't handle fractional values. Why didn't they implement this with a call to AddTicks and handle the fraction properly? Or at least take an int, so it's transparent to callers?

I'm guessing there must be a good reason why they implemented it this way, but I can't think of what it could be. Can anyone offer any insight?

EDIT: just to further emphasise the point:

AddSeconds(1.5); // Adds 1500 milliseconds
like image 283
fearofawhackplanet Avatar asked Apr 22 '10 10:04

fearofawhackplanet


1 Answers

It is a compromise, not an entirely unreasonable one. The passed argument has to be rounded to deal with the resolution of DateTime. Rounding to the accuracy of a tick (100 nanoseconds) is a problem. Double doesn't have enough significant digits to be able to span the full range of possible dates. 10000 years x 365 x 24 x 3600 x 1000 x 10000 = 3E18, double has only 15 significant digits. There is no problem by rounding to a millisecond, 3E14 is just good enough (what are the odds?)

The workaround is simple, just use AddTicks(1.5 * 10000).

like image 64
Hans Passant Avatar answered Oct 13 '22 10:10

Hans Passant