title: How to initialize timespec from a double
body: <p>I want to initialize a timespec structure from a double. How can I achieve accurate conversion of the fractional part to nanoseconds?</p>
  
  <pre><code>double x = 10.1;
  struct timespec tp;
  tp.tv_sec = (long) x;
  tp.tv_nsec = (x - tp.tv_sec) * 1000000000L;
  printf("%ld %ld\n", tp.tv_sec, tp.tv_nsec);
  // 10 99999999  &lt;- actual (BAD)
  // 10 100000000 &lt;- expected
  </code></pre>
  
  <p>That seems like a classical floating point challenge. The exact method used to extract integral and fractional does not matter (ex modf).</p>
  
  <p>My current workaround is to convert the double to a string rounded to the desired precision and to extract both parts. </p>
  
  <pre><code>static const int CLOCK_PRECISION = 1;
  char nanos[] = "000000000";
  char str[25]; // arbitrary size suits my needs
  /** Converted string length (excluding '\0'). */
  int len = snprintf(str, sizeof(str), "%.*f", CLOCK_PRECISION, b);
  /** Position of first decimal digit in the string. */
  char *decOfs = strchr(str, '.') + 1;
  /** Number of decimal digits. */
  size_t decLen = len - (decOfs - str);  
  memcpy(nanos, decOfs, decLen);  
  a-&gt;tv_sec  = atol(str);
  a-&gt;tv_nsec = atol(nanos);
  </code></pre>
  
  <p>I even contemplate a variant of my workaround that would init directly from a string (ex: "10.1"). This would be viable because my initialization values do not change over time. </p>
  
  <p>Any solution to my initial problem?
  Any better ideas to initialize a timespec?</p>
  
  <p>I want a scalable solution. I do not want to init from tenths or hundredths of seconds.</p>