title: Accuracy of nanosecond component in Ruby Time
body: <p>I have a duration in seconds with millisecond precision, 420.854 (420 seconds and 854 milliseconds).</p>
  
  <p>I want to format it like (Minutes):(Seconds).(Milliseconds) so I tried this:</p>
  
  <pre><code>Time.at(421.854).utc.strftime('%M:%S.%L')
  </code></pre>
  
  <p>The result: <code>"07:01.853"</code> As you can see it's off by one millisecond.</p>
  
  <p>So I dug into it further:</p>
  
  <pre><code>Time.at(421.854).nsec # Output: 853999999 (expected 854000000)
  </code></pre>
  
  <p>I believe the unexpected output of the above is the cause of the problem. Some numbers work as expected though for example:</p>
  
  <pre><code>Time.at(421.855).nsec # Output 855000000 as expected
  </code></pre>
  
  <p>Does anyone have any suggestions on solving this, the best I can come up with is to "fix" the nanosecond component afterwards with <code>(nanoseconds.to_f / 1000000).round * 1000000</code> but I feel like there might be a better approach. Really appreciate any thoughts on the subject.</p>
  
  <p>Thanks.</p>