When casting float to int the decimal is discarded. What\'s a clean way to cast so that it rounds to the nearest whole number instead.
x := int(3.6)
sho
You could use int(math.Round(f))
to round to the nearest whole number when converting a float to an int in Go. The decimal is also discarded when a float is set to a byte or a rune. Truncation doesn't happen when it's set to a string or a bool.
package main
import (
. "fmt"
. "math"
)
func main() {
f := 3.6
c := []interface{}{byte(f), f, int(Round(f)), rune(f), Sprintf("%.f", f), f != 0}
checkType(c)
}
func checkType(s []interface{}) {
for k, _ := range s {
Printf("%T %v\n", s[k], s[k])
}
}
Round returns the nearest integer, rounding half away from zero. See https://golang.org/pkg/math/#Round. See https://stackoverflow.com/a/61503758/12817546.
f := 3.6
truncates to “uint8 3”, f
is “float64 3.6”, int(Round(f))
rounds up to “int 4”, rune(f)
truncates to “int32 3”, Sprintf("%.f", f)
is “string 3.6” and f != 0
outputs “bool true”.
int(f+0.5)
will cause for it to round upwards if it's >= .5