Limit Duration granularity

I've calculated a Duration by subtracting a saved time from the current time: time.Now().Sub(oldTime)

Printing it gives me this: 1m30.789260489s

1m30.79s would look better, where I'm using it. How can I truncate / reduce the granularity of a Duration in Go?

Upvotes: 1

Views: 197

Answers (1)

peterSO
peterSO

Reputation: 166714

Package time

import "time"

func (Duration) Round 1.9

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

func (Duration) Truncate 1.9

func (d Duration) Truncate(m Duration) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.


Use the Round or Truncate methods on the time.Duration.


For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    d, err := time.ParseDuration("1m30.789260489s")
    if err != nil {
        panic(err)
    }
    fmt.Println(d)
    fmt.Println(d.Round(10 * time.Millisecond))
}

Playground: https://play.golang.org/p/8b3xAxfSE90

Output:

1m30.789260489s
1m30.79s

Upvotes: 1

Related Questions