How to Convert an Integer to a Float Number in Go
Created
Modified
Using float64 Function
The easiest way to convert an integer to a float number in Golang:
package main
import "fmt"
func main() {
i := 6
f := float64(i)
fmt.Printf("%T: %f\n", f, f)
fmt.Printf("%T: %.3f\n", f, f)
f32 := float32(i)
fmt.Printf("%T: %f\n", f32, f32)
}
float64: 6.000000 float64: 6.000 float32: 6.000000
Proper parentheses placement is key:
For example,
package main
import "fmt"
func main() {
i := 1234
f := float64(i) / 10.0
fmt.Printf("%T: %f\n", f, f)
// wrong
f = float64(i / 10.0)
fmt.Printf("%T: %f\n", f, f)
}
float64: 123.400000 float64: 123.000000