golang中float类型转换成int类型

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

posted @ 2021-12-19 12:01  专职  阅读(6467)  评论(0编辑  收藏  举报