找了很多关于go的四舍五入文章,发现没有这种类似的包,只能自己写一个了,也是看到别人的取巧方案,在这个基础上扩展的:
```go
//四舍五入
func Round(x float64,digit int) (number float64,err error){
baseDigit := 10
if digit < 0 {
return x,errors.New("错误的精度,不能小于0")
}else{
baseDigit = pow(baseDigit,digit+1)
}
betweenNumber := float64(5)
return (math.Floor((x * float64(baseDigit) + betweenNumber)/10))/float64(baseDigit/10),err
}
//获取需要的次方
func pow(x, n int) int {
ret := 1 // 结果初始为0次方的值,整数0次方为1。如果是矩阵,则为单元矩阵。
for n != 0 {
if n%2 != 0 {
ret = ret * x
}
n /= 2
x = x * x
}
return ret
}
func main(){
x := 74.96
y := 20.48
z := x - y
fmt.Println(z) //output: 54.47999999999999
roundMath,err = float.Round(z,2)
fmt.Println(roundMath) //output: 54.48
fmt.Println(err)
z = 0.6
fmt.Println(z + 0.7) //output: 1.2999999999999998
roundMath,err = float.Round(z+0.7,2)// 1.3
fmt.Println(roundMath)
fmt.Println(err)
}
```
运行结果示意图:
![运行结果.png](https://static.studygolang.com/200910/787dff416bb96a46d907255c1c862081.png)
有疑问加站长微信联系(非本文作者))