Convert String to int, float, uint or boolean in Go

Convert String to int, float, uint or boolean in Go

GoLang is statically typed language and it supports different datatypes. In real world application we come across the situation where one has to convert the data type from one to another. Here in this example we will be covering different ways to convert string to other data type like int,  float, uint or boolean.

package main

import (

func main() {
	fmt.Println("Convert string to int")
	str_int := "10"
	val_int, _ := strconv.ParseInt(str_int, 10, 64)
	fmt.Printf("%d\n", val_int)

	fmt.Println("Convert string to int using atoi")
	val_atoi, _ := strconv.Atoi(str_int)
	fmt.Printf("%d\n", val_atoi)

	fmt.Println("Convert string to boolean")
	str_bool := "true"
	val_bool, _ := strconv.ParseBool(str_bool)
	fmt.Printf("%b\n", val_bool)

	fmt.Println("Convert string to float")
	str_float := "123.23"
	val_float, _ := strconv.ParseFloat(str_float, 64)
	fmt.Printf("%f\n", val_float)

	fmt.Println("Convert string to unsigned int")
	str_uint := "1234"
	val_uint, _ := strconv.ParseUint(str_uint, 10, 64)
	fmt.Printf("%d\n", val_uint)


Convert string to int
Convert string to int using atoi
Convert string to boolean
Convert string to float
Convert string to unsigned int

Stay tuned for more examples and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *