core.time Duration how to get units in double/float format?
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jan 18 04:46:31 PST 2016
On Sunday, January 17, 2016 14:43:26 Borislav Kosharov via Digitalmars-d-learn wrote:
> Seeing that TickDuration is being deprecated and that I should
> use Duration instead, I faced a problem. I need to get total
> seconds like a float. Using .total!"seconds" returns a long and
> if the duration is less than 1 second I get 0. My question is
> whats the right way to do it. Because I saw that TickDuration has
> a to!("seconds", float) method, but Duration doesn't have one. I
> can convert Duration to TickDuration and call to but seeing that
> its deprecated makes me think there is a better way.
In general, using floating point values with time is an incredibly bad idea.
It can certainly make sense when printing stuff out, but using it in
calculations is just asking for trouble given all of the unnecessary
imprecision that it adds. So, Duration does not directly support floating
point values at all, and that's very much on purpose. I'd strongly argue
that the fact that TickDuration does was a mistake.
So, if you're doing floating point calculations with time, I'd strongly urge
you to rethink your code. And if you're just trying to print out the a
duration as a floating point value, because it's nice to view that way, then
that's fine, but you'll need to do the conversion yourself. And it's not
that hard. It just isn't handed to you directly, because aside from
printing, code really shouldn't be using floating point values for time.
e.g.
string toFloatingSeconds(Duration d)
{
import std.conv;
enum hnsecsPerSecond = convert!("seconds", "hnsecs")(1);
auto s = d.split!("seconds", "hnsecs")();
return to!string(s.seconds + cast(real)(s.hnsecs) / hnsecsPerSecond);
}
And yes, that's a bit more of a pain than using to!("seconds", float) with
TickDuration, but it's also the sort of thing that most code really
shouldn't be doing. So, adding that functionality to Duration would just
encourage folks to write buggy code.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list