在 Go 语言中,可以使用标准库中的 math 包中的 Round 函数来进行四舍五入操作。

具体用法如下:

import "math"

// 四舍五入函数,保留 n 位小数
func Round(f float64, n int) float64 {
    pow10_n := math.Pow10(n)
    return math.Round(f*pow10_n) / pow10_n
}

其中,f 要进行四舍五入的浮点数,n 表示保留多少位小数。

例如:

fmt.Println(Round(3.1415926, 2)) // 输出:3.14
fmt.Println(Round(3.1455926, 2)) // 输出:3.15

注意,math 包中的 Round 函数默认是对最近的偶数进行舍入,不是直接的四舍五入,所以需要进行一些处理才能得到我们想要的结果。

Go 语言四舍五入实现 - 使用 math.Round 函数

原文地址: https://www.cveoy.top/t/topic/lEaE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录