fearofawhackplanet
fearofawhackplanet

Reputation: 53396

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

Upvotes: 8

Views: 1743

Answers (4)

Oded
Oded

Reputation: 499042

From MSDN:

The milliseconds value is rounded to the nearest integer before it is added to the specified DateTime.

As DateTime can't resolve anything less then milliseconds, adding fractional milliseconds would also be the wrong thing to do.

I would say they have made a compromise - it is better then throwing an exception and would work as most programmers would expect.

Upvotes: -1

Hans Passant
Hans Passant

Reputation: 941585

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

Upvotes: 5

Richard
Richard

Reputation: 109015

DateTime and TimeSpan do some rounding. But knowing Ticks are 100ns intervals you can work around this:

var now = DateTime.Now;
var result = now + TimeSpan.FromTicks(10000 * 1.5);

(There are 10,000 100ns intervals in 1ms.)

EDIT: Corrected this, DateTime stores count of *100*ns internals (not 10ns).

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

It does seem rather bizarre. My only thought is that perhaps they felt it better to round to the nearest millisecond, rather than risk the caller truncating a double to an int. Yes, this is a rather feeble explanation. Sorry.

Upvotes: 2

Related Questions