In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration ‘d’ to the closest multiple of ‘m’ duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Round(m Duration) Duration
Here, d is the duration of time that will be rounded and m is the closest multiple.
Return value: It returns maximum (or minimum) duration if the outcome surpasses the maximum (or minimum) value that could be stored in a duration. But if m is less than or equal to 0 then it returns unaltered ‘d’.
Example 1:
package main
import (
"fmt"
"time"
)
func main() {
d, _ := time.ParseDuration("5m7s")
fmt.Printf("Rounded d is : %s",
d.Round(6*time.Second))
}
|
Output:
Rounded d is : 5m6s
Here, ‘d’ is rounded to the closest multiple of m.
Example 2:
package main
import (
"fmt"
"time"
)
func main() {
d, _ := time.ParseDuration("3m73.671s")
R := []time.Duration{
time.Microsecond,
time.Second,
3 * time.Second,
9 * time.Minute,
}
for _, m := range R {
fmt.Printf("Rounded(%s) is : %s\n",
m, d.Round(m))
}
}
|
Output:
Rounded(1µs) is : 4m13.671s
Rounded(1s) is : 4m14s
Rounded(3s) is : 4m15s
Rounded(9m0s) is : 0s
Here, an array of ‘d’ is formed first then a range is used in order to iterate over all the values of d. And at last Round() method is used to print all the rounded values of d.
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
21 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...