Convert float64 to int in Go

How to convert float64 to int in Go? I know that the strconv package can be used to convert something to or from a string, but not between data types where one is not a string. I know that I can use fmt.Sprintf to convert something to a string, and then strconv to the data type I need, but this extra conversion seems a bit awkward - is there a better way to do this?

+97
go
Nov 05 '11 at 18:43
source share
3 answers
 package main import "fmt" func main() { var x float64 = 5.7 var y int = int(x) fmt.Println(y) // outputs "5" } 
+161
Nov 05 '11 at 19:44
source share

A simple cast in int truncates the float, which if your system internally represents 2.0 as 1.9999999999, you will not get what you expect. Various printf conversions handle this and correctly round the number when converting. To get a more accurate value, the conversion is even harder than you might expect:

 package main import ( "fmt" "strconv" ) func main() { floats := []float64{1.9999, 2.0001, 2.0} for _, f := range floats { t := int(f) s := fmt.Sprintf("%.0f", f) if i, err := strconv.Atoi(s); err == nil { fmt.Println(f, t, i) } else { fmt.Println(f, t, err) } } } 

Code for Go to the site

+6
Apr 08 '16 at 16:52
source share

If its just from float64 to int, this should work

 package main import ( "fmt" ) func main() { nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0} //round fmt.Printf("Round : ") for _, f := range nf { fmt.Printf("%d ", round(f)) } fmt.Printf("\n") //rounddown ie. math.floor fmt.Printf("RoundD: ") for _, f := range nf { fmt.Printf("%d ", roundD(f)) } fmt.Printf("\n") //roundup ie. math.ceil fmt.Printf("RoundU: ") for _, f := range nf { fmt.Printf("%d ", roundU(f)) } fmt.Printf("\n") } func roundU(val float64) int { if val > 0 { return int(val+1.0) } return int(val) } func roundD(val float64) int { if val < 0 { return int(val-1.0) } return int(val) } func round(val float64) int { if val < 0 { return int(val-0.5) } return int(val+0.5) } 

Outputs:

 Round : -2 -2 -2 0 2 2 2 RoundD: -2 -3 -3 0 1 2 2 RoundU: -1 -2 -2 0 2 3 3 

Here's the code on the playground - https://play.golang.org/p/HmFfM6Grqh

+6
May 16 '16 at 6:16
source share



All Articles