The math.Floor
in Golang returns a float64. But I would like it to return an integer. How can I get the integer value after performing the floor
operation? Can I just use int(x)
or int32(x)
or int64(x)
? I worry that the integer range might not match that of a float64 result therefore brings inaccuracy to the operation.
You may just want to check beforehand; if the conversion will perform safely or an overflow will occur.
As John Weldon suggested,
package main
import (
"fmt"
"math"
)
func main() {
var (
a int64
f64 float64
)
// This number doesn't exist in the float64 world,
// just a number to perform the test.
f64 = math.Floor(9223372036854775808.5)
if f64 >= math.MaxInt64 || f64 <= math.MinInt64 {
fmt.Println("f64 is out of int64 range.")
return
}
a = int64(f64)
fmt.Println(a)
}
Go Playground
I hope this will answer your question.
Also, I'd really like to know if any better solution is available. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With