# Converting a Duration to a Double of seconds?

perhaps i am going crazy, but is there really no standard library API to convert a `Duration` to a `Double` of (milli)seconds?

next best thing i could think of is dividing by `milliseconds(1)`. but this seems less efficient than doing the arithmetic manually.

``````let milliseconds:Double = duration / .milliseconds(1)
``````

You’d compute it from `components`:

``````let seconds = Double(duration.components.seconds)
``````

this loses the fractional component though?

Ah, your question was ambiguous on that point; you'd add the `attoseconds` component back (appropriately scaled) for the fractional component, of course.

Will this work?

extension Duration {
var inMilliseconds: Double {
Double((self * 1000).components.seconds)

Edit: no, that was not correct, this one is better:

``````extension Duration {
var inMilliseconds: Double {
let v = components
return Double(v.seconds) * 1000 + Double(v.attoseconds) * 1e-15
}
}
``````

Gee, I've just corrected another mistake (was multiplying integer seconds - which may overflow) Shouldn't this be in the standard library or was it deliberately not included?

1 Like