Convert float type to int type in go

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

output result:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish