在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的Round()函数用于查找将规定的持续时间‘d’舍入为‘m’持续时间的最接近倍数的结果。在这里,中间值的舍入方式是舍入到远离0的舍入。此外,此函数在时间包下定义。在这里,您需要导入“time”包才能使用这些函数。
用法:
func (d Duration) Round(m Duration) Duration
此处,d是要舍入的时间长度,而m是最接近的倍数。
返回值:如果结果超过持续时间中可以存储的最大(或最小)值,则返回最大(或最小)持续时间。但是,如果m小于或等于0,则它返回未更改的‘d’。
范例1:
// Golang program to illustrate the usage of
// Round() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Calling main
func main() {
// Defining duration
// of Round method
d, _:= time.ParseDuration("5m7s")
// Prints rounded d
fmt.Printf("Rounded d is:%s",
d.Round(6*time.Second))
}
输出:
Rounded d is:5m6s
在此,将‘d’舍入为m的最接近倍数。
范例2:
// Golang program to illustrate the usage of
// Round() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Calling main
func main() {
// Defining duration of Round method
d, _:= time.ParseDuration("3m73.671s")
// Array of m
R:= []time.Duration{
time.Microsecond,
time.Second,
3 * time.Second,
9 * time.Minute,
}
// Using for loop and range to
// iterate over an array
for _, m:= range R {
// Prints rounded d of all
// the items in an array
fmt.Printf("Rounded(%s) is:%s\n",
m, d.Round(m))
}
}
输出:
Rounded(1µs) is:4m13.671s Rounded(1s) is:4m14s Rounded(3s) is:4m15s Rounded(9m0s) is:0s
在此,首先形成一个‘d’数组,然后使用一个范围来迭代所有d值。最后,使用Round()方法来打印d的所有舍入值。
相关用法
- Golang math.Lgamma()用法及代码示例
- Golang math.Float64bits()用法及代码示例
- Golang atomic.AddInt64()用法及代码示例
- Golang atomic.StoreInt64()用法及代码示例
- Golang reflect.FieldByIndex()用法及代码示例
- Golang string.Contains用法及代码示例
- Golang bits.Sub()用法及代码示例
- Golang io.PipeWriter.CloseWithError()用法及代码示例
- Golang reflect.AppendSlice()用法及代码示例
- Golang reflect.ChanOf()用法及代码示例
- Golang flag.Bool()用法及代码示例
- Golang time.Sleep()用法及代码示例
- Golang time.Time.Year()用法及代码示例
- Golang reflect.DeepEqual()用法及代码示例
- Golang reflect.Indirect()用法及代码示例
- Golang reflect.CanAddr()用法及代码示例
- Golang reflect.CanInterface()用法及代码示例
- Golang reflect.CanSet()用法及代码示例
- Golang reflect.Cap()用法及代码示例
- Golang strings.ContainsRune()用法及代码示例
注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 time.Round() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。