How to do rounding in math/big float?

Viewed 1242

I have a big.Float, in the golang standard math/big library, and I want to round it into the nearest big.Int. I don't know how.

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())
}
1 Answers

You may add 0.5 to it before calling Float.Int(), and you get what you want.

At least for positive numbers. If the number is negative, you have to add -0.5 so e.g. -0.6 gets "rounded" to -1.0.

This is how you can do that:

delta := 0.5
if bf.Sign() < 0 {
    delta = -0.5
}
bf.Add(bf, new(big.Float).SetFloat64(delta))
bint, _ := bf.Int(nil)

You may simplify this addition like this if you want to:

bf.Add(bf, new(big.Float).SetFloat64(0.5*float64(bf.Sign())))

Let's test it for some values:

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)
}

Output (try it on the Go Playground):

 -0.8 => -1
 -0.3 =>  0
  0.6 =>  1
  1.1 =>  1
  1.8 =>  2
Related