将math.Floor在Golang返回float64.但我希望它返回一个整数.如何在执行floor操作后获取整数值?我可以只使用int(x)或int32(x)或int64(x)?我担心整数范围可能与float64结果的范围不匹配,因此会给操作带来不准确性.
你可能只是想事先检查一下; 如果转换将安全执行或将发生溢出.
正如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)
我希望这能回答你的问题.
另外,我真的想知道是否有更好的解决方案.:)
| 归档时间: |
|
| 查看次数: |
2933 次 |
| 最近记录: |