如何从golang的数学楼层函数中获取整数结果?

new*_*guy 4 go

math.Floor在Golang返回float64.但我希望它返回一个整数.如何在执行floor操作后获取整数值?我可以只使用int(x)int32(x)int64(x)?我担心整数范围可能与float64结果的范围不匹配,因此会给操作带来不准确性.

Joh*_*don 6

你可以用比较float64值math.MaxInt64math.MinInt64做转换之前.


Moh*_*sin 6

你可能只是想事先检查一下; 如果转换将安全执行或将发生溢出.

正如John Weldon所说,

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)
}
Run Code Online (Sandbox Code Playgroud)

去游乐场

我希望这能回答你的问题.
另外,我真的想知道是否有更好的解决方案.:)