如何在golang中使用math.Floor函数获得整数结果?

7
在Golang中,math.Floor返回一个float64值。但是我想要返回一个整数。如何得到执行floor操作后的整数值?可以使用int(x)int32(x)int64(x)吗?我担心整数范围可能与float64结果不匹配,因此会带来不准确性问题。
2个回答

10

您可能需要在进行转换之前先检查,以确保转换是安全的,不会发生溢出。

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

Go Playground

我希望这会回答你的问题。
同时,我也很想知道是否有更好的解决方案。 :)


8

在进行转换之前,您可以将float64值与math.MaxInt64math.MinInt64进行比较。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接