go - 如何在数学/大浮点数中进行舍入?
问题描述
我有一个big.Float
, 在 golang 标准math/big
库中,我想将它四舍五入到最近的big.Int
. 我不知道怎么做。
package main
import (
"fmt"
"math/big"
)
func main() {
bfloat, _ := (&big.Float{}).SetString("1.8")
// what to do here to round bfloat to nearest int?
bint, _ := bfloat.Int(nil) // not this, this truncates
fmt.Println(bint.String())
}
解决方案
您可以在调用之前添加 它,然后得到您想要的。0.5
Float.Int()
至少对于正数。如果该数字为负数,则必须添加-0.5
例如-0.6
“四舍五入”为-1.0
。
您可以这样做:
delta := 0.5
if bf.Sign() < 0 {
delta = -0.5
}
bf.Add(bf, new(big.Float).SetFloat64(delta))
bint, _ := bf.Int(nil)
如果您愿意,可以像这样简化此添加:
bf.Add(bf, new(big.Float).SetFloat64(0.5*float64(bf.Sign())))
让我们测试它的一些值:
for _, s := range []string{"-0.8", "-0.3", "0.6", "1.1", "1.8"} {
bf, _ := (&big.Float{}).SetString(s)
delta := 0.5
if bf.Sign() < 0 {
delta = -0.5
}
bf.Add(bf, new(big.Float).SetFloat64(delta))
bint, _ := bf.Int(nil)
fmt.Printf("%5s => %2s\n", s, bint)
}
输出(在Go Playground上试试):
-0.8 => -1
-0.3 => 0
0.6 => 1
1.1 => 1
1.8 => 2
推荐阅读
- android - 从 Activity 导航到 Fragment 并返回到 Activity 导致该 Activity 被多次创建
- android - 如何在相对布局中设置带有 web 视图的广告而不重叠?
- python - 是否可以在 GEKKO 动态优化中定义变量的开始和结束时间?
- vue.js - 在vuejs中更改按钮开关切换
- python - 在使用诗歌安装 Django 后,它在活动 venv 中显示“没有名为 django 的模块”
- html - 使用列设置响应式弹性框
- javascript - 当有其他重新渲染正在进行时,React 计时器不会更新
- spring - 无法在 spring 模块集成测试中自动创建表
- azure-data-explorer - Azure 数据资源管理器:如何从存储的函数中将行引入表中
- java - 如何将 Hibernate 6 与 Quarkus 一起使用