golang中float类型转换成int类型

时间:2022-12-19 13:23:23
package main

import (
"fmt"
"strconv"
) func f2i(f float64) int {
i, _ := strconv.Atoi(fmt.Sprintf("%1.0f", f))
return i
} func main() {
var floats = []float64{7.9991, 10.0, 11.1111, 12.5, 12.6, 11.5} for _, f := range floats {
println(fmt.Sprintf("%1.5f", f), f2i(f))
}
}

输出结果:

7.99910 8
10.00000 10
11.11110 11
12.50000 12
12.60000 13
11.50000 12

参考链接 https://golangtc.com/t/5624a947b09ecc56ca000107