首页 > 解决方案 > 如何在数学/大浮点数中进行舍入?

问题描述

我有一个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())
}

标签: go

解决方案


您可以在调用之前添加 它,然后得到您想要的。0.5Float.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

推荐阅读