Essential Go Basic types  Edit on GitHub      File Issue

Floating-point numbers

Go has floating point numbers corresponding to the IEEE 754 standard:

Zero value of float32 and float64 is 0.0.

Convert floats to strings with FormatFloat

var f32 float32 = 1.3
s1 := strconv.FormatFloat(float64(f32), 'E', -1, 32)
fmt.Printf("f32: %s\n", s1)

var f64 float64 = 8.1234
s2 := strconv.FormatFloat(f64, 'e', -1, 64)
fmt.Printf("f64: %s\n", s2)
f32: 1.3E+00
f64: 8.1234e+00

Convert floats to strings with Sprintf

var f64 float64 = 1.54
s := fmt.Sprintf("%f", f64)
fmt.Printf("f is: '%s'\n", s)
f is: '1.540000'

Using strconv.FormatFloat is faster than fmt.Sprintf.

Convert string to float with ParseFloat

s := "1.2341"
f, err := strconv.ParseFloat(s, 64)
if err != nil {
	log.Fatalf("strconv.ParseFloat() failed with '%s'\n", err)
}
fmt.Printf("f: %f\n", f)
f: 1.234100

Convert string to float with Sscanf

s := "1.2341"
var f float64
_, err := fmt.Sscanf(s, "%f", &f)
if err != nil {
	log.Fatalf("fmt.Sscanf failed with '%s'\n", err)
}
fmt.Printf("f: %f\n", f)
f: 1.234100
  ↑ ↓ to navigate     ↵ to select     Esc to close