Essential Go Basic types  Suggest an edit

Floating-point numbers

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

Zero value of float32 and float64 is 0.0.

Convert float to string with FormatFloat

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

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

Convert float to string 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"
f64, err := strconv.ParseFloat(s, 64)
if err != nil {
	log.Fatalf("strconv.ParseFloat() failed with '%s'\n", err)
}
fmt.Printf("f64: %f\n", f64)
f64: 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