On Tuesday, September 2, 2014 8:16:04 PM UTC-7, Gary Scarr wrote:
Bravo Andrew!!!
This is indeed what I had been wanting: the automatic formatting range of
the existing Duration with the arbitrary precision of the Time.Round
function. With all due respect to Rob with his "Just write the code", it
didn't seem that obvious and I would certainly never have come up with
anything this elegant.
With all due respect to Rob, my solution was elegant and quick to arrive at
because I basically jacked it from the standard library. You mentioned
Time.Round <
http://golang.org/pkg/time/#Time.Round> so I took a peek at the
source <
http://golang.org/src/pkg/time/time.go?s=32024:32060#L1097>. From
there it just took a couple minutes. In my experience, if you want to do
something similar to the standard library it's usually a good idea to start
by reading it... and then maybe by stealing from it.
My first instinct was along the lines of Jan's:( (dur +
resolution/2)/resolution) * resolution but there's no hint of a 2 in your
code so it will take me a while to grok it. But it does far better than my
simple rounding of both timing endpoints so it doesn't affect their
precision.
There's a hint of a 2 with "m+m" ;)
As is often the case, after posing my "simple" question and then being
asked "Is this what you want" it occurred to me that what might also be
useful was to print a duration with a "sensible" precision like 2 or 3
digits. Is there a way to use your function (other than a switch or
if/else chain based on the value of d) that would achieve this? I tried a
very naive making r a function of d as here where n was intended to be the
approx digits of precision but it failed horribly:
switch n {
case 1:
r = d / 10
case 2:
r = d / 100
case 3:
r = d / 1000
case 4:
r = d / 10000
case 5:
r = d / 100000
case 6:
r = d / 10000000
}
Because it was kind of fun, here's a significant figure rounding function:
http://play.golang.org/p/WjfKwhhjL5. I cheated a bit with math.Pow10
<
http://golang.org/pkg/math/#Pow10>. If you want anything more custom than
that (e.g. "3.22h", "15.7m", etc.), you'll need to write your own string
conversion function. In which case, this
<
http://golang.org/src/pkg/time/time.go?s=15097:15130#L454> would be a good
place to start.
Thanks to you and all the others for your suggestions,
Gary
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.