Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an integer result from the math floor function in golang?

Tags:

go

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.

like image 619
newguy Avatar asked Dec 07 '22 16:12

newguy


1 Answers

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. :)

like image 111
Mohsin Avatar answered Dec 11 '22 10:12

Mohsin