Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does TimeSpan.FromSeconds(double) round to milliseconds?

TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

TimeSpan.FromSeconds(0.12345678).TotalSeconds     // 0.123 TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds     // 0.1234567 
like image 968
Roman Starkov Avatar asked Jan 12 '11 18:01

Roman Starkov


2 Answers

As you've found out yourself, it's a documented feature. It's described in the documentation of TimeSpan:

Parameters

value Type: System.Double

A number of seconds, accurate to the nearest millisecond.

The reason for this is probably because a double is not that accurate at all. It is always a good idea to do some rounding when comparing doubles, because it might just be a very tiny bit larger or smaller than you'd expect. That behaviour could actually provide you with some unexpected nanoseconds when you try to put in whole milliseconds. I think that is the reason they chose to round the value to whole milliseconds and discard the smaller digits.

like image 125
GolezTrol Avatar answered Sep 27 '22 19:09

GolezTrol


On the rights of a speculation..

  1. TimeSpan.MaxValue.TotalMilliseconds is equat to 922337203685477. The number that has 15 digits.
  2. double is precise to 15 digits.
  3. TimeSpan.FromSeconds, TimeSpan.FromMinutes etc. all go through conversion to milliseconds expressed in double (then to ticks then to TimeSpan which is not interesting now)

So, when you are creating TimeSpan that will be close to TimeSpan.MaxValue (or MinValue) the conversion will be precise to milliseconds only.
So the probable answer to the question "why" is: to have the same precision all the times.
Further thing to think about is whether the job could have been done better if conversions were done through firstly converting value to ticks expressed in long.

like image 42
alpha-mouse Avatar answered Sep 27 '22 21:09

alpha-mouse