Golang 四舍五入:使用 math.Round 函数实现保留小数位
Golang 提供了一个内置的 'math' 包,其中包含了一个 'Round' 函数,可以实现四舍五入的功能。
import "math"
func main() {
x := 3.1415926
rounded := math.Round(x * 100) / 100
fmt.Println(rounded) // 输出 3.14
}
在这个例子中,我们将 'x' 的值乘以 100,然后使用 'Round' 函数将结果四舍五入到最接近的整数。最后,我们再将结果除以 100,以得到保留两位小数的结果。
原文地址: https://www.cveoy.top/t/topic/lEa0 著作权归作者所有。请勿转载和采集!