Integer and float conversion to string and vice versa in Golang

To convert string to Integer value in Golang you need to import strconv library, then call Atoi function as:

 intval, err := strconv.Atoi("123")

to convert string to float call ParseFloat method:

    floatval, err := strconv.ParseFloat("12.1", 0)

To convert Integer to string use Itoa method:

    str := strconv.Itoa(45)

To convert float to string use FormatFloat method:

    str := strconv.FormatFloat(45.124, 'f', 2, 32)

‘f’ is format type, 2 is decimal points, and 32 is bit size

Sprintf method of fmt library could be used instead to return formatted float string:

    str := fmt.Sprintf("%.2f", 45.124)

f is format type (float) and .2 represents two decimal points

Leave a Reply