Convert to int, float

suggest change

There are multiple ways to convert a string to a number (int, float32, float64).

s := "234"
i, err := strconv.Atoi(s)
if err != nil {
	fmt.Printf("strconv.Atoi() failed with: '%s'\n", err)
}
fmt.Printf("strconv.Atoi('%s'): %d\n", s, i)

i, err = strconv.Atoi("not a number")
if err != nil {
	fmt.Printf("strconv.Atoi('not a number') failed with: '%s'\n", err)
}

i64, err := strconv.ParseInt(s, 10, 64)
if err != nil {
	fmt.Printf("strconv.ParseInt() failed with: '%s'\n", err)
}
fmt.Printf("strconv.ParseInt('%s', 64): %d\n", s, i64)

s = "-3.234"
f64, err := strconv.ParseFloat(s, 64)
if err != nil {
	fmt.Printf("strconv.ParseFloat() failed with: '%s'\n", err)
}
fmt.Printf("strconv.ParseFloat('%s', 64): %g\n", s, f64)

var f2 float64
_, err = fmt.Sscanf(s, "%f", &f2)
if err != nil {
	fmt.Printf("fmt.Sscanf() failed with: '%s'\n", err)
}
fmt.Printf("fmt.Sscanf(): %g\n", f2)
strconv.Atoi('234'): 234
strconv.Atoi('not a number') failed with: 'strconv.Atoi: parsing "not a number": invalid syntax'
strconv.ParseInt('234', 64): 234
strconv.ParseFloat('-3.234', 64): -3.234
fmt.Sscanf(): -3.234

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents