AppDividend
Latest Code Tutorials

How To Convert Golang String To Int Example Tutorial

Golang has an inbuilt package called strconv that provide functions that convert string to int. The Atoi() Sscanf(), and ParseInt() are three functions that convert Golang string to int. Go is the statically typed language, data types are bound to variables rather than its values. What does that mean is that if you define the variable as int, it can only be int; you can’t assign the string to it without converting the string data type of a variable.

How To Convert Golang String To Int

Go is statically typed. Every variable has the static type, that is, precisely one type known and fixed at compile time: int, float32, *MyType, []byte, and so on.  In Go, data types are used to distinguish one specific type of data, defining the values that you can assign to a type and the operations you can execute on it.  In programming, there are times when you will need to convert values between types to modify values differently. So, type conversion in Golang is one of the most important topics.

There are three ways you can convert go string to integer(number).

  1. strconv.Atoi()
  2. strconv.ParseInt()
  3. fmt.Sscanf()

Convert string to int with strconv.Atoi(str)

Golang strconv.Atoi() function returns its value of type int. If the str is a valid input, then the function returns the equivalent integer number for the passed string number. Atoi stands for ASCII to integer.

If no valid conversion takes place, then the function returns zero.

See the following code.

// hello.go

package main

import (
	"fmt"
	"strconv"
)

func main() {
	data := "11"
	if sv, err := strconv.Atoi(data); err == nil {
		fmt.Printf("%T, %v", sv, sv)
	}
}

Output

go run hello.go
int, 11

We have defined a string called “11” and use Atoi() function to convert string to an integer.

Then we have used the fmt verbs to print the converted data type and value.

From the above example, we can see that it convert string “11” to integer 11.

In the above code example, we have taken an integer 11 and make it string by putting ” “, so after converting to an integer, it will be like 11, which is an ordinary integer, but let’s try to convert “Golang” string and see the output.

// hello.go

package main

import (
	"fmt"
	"strconv"
)

func main() {
	data := "Golang"
	sv, err := strconv.Atoi(data)
	if err == nil {
		fmt.Printf("%T, %v", sv, sv)
	} else {
		fmt.Println(err)
	}
}

In the above code, our data is “Golang,” which is a string.

Now, strconv.Atoi() function will return an error because the “Golang” string will be counted as invalid syntax and throws an error like the following.

strconv.Atoi: parsing “Golang”: invalid syntax

Output

go run hello.go
strconv.Atoi: parsing "Golang": invalid syntax

You can use strconv.Atoi(s) to convert a string s to a 32-bit integer. Atoi() function is equivalent to ParseInt(s, 10, 0) function, converted to type int.

Parsing a Custom string to int in Golang

There is also Golang fmt.Sscanf(), which gives even greater flexibility as with a format string, you can specify the number format (like width, base, etc.) along with some additional extra characters in the input string. Let’s deep dive into Golang fmt.Sscanf() function.

func Sscanf()

Golang Sscanf() function scans the argument string, storing successive space-separated values into successive arguments as defined by the format.

The Sscanf() returns the number of items successfully parsed. The newlines in the input must match newlines in the format.

See the following code example.

// hello.go

package main

import (
	"fmt"
)

func main() {
	s := "id:00211"

	var i int
	if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
		fmt.Println(i)
	}
}

Output

go run hello.go
211

Here our input is provided in the form of “id:00211” where you have the prefix “id:” and the number is fixed 5 digits, padded with zeros if shorter, this is very quickly parsable. That is why we got 211 in the output.

With this Sscanf() method, we must specify the format string to guide the parsing of the values. We can use the standard format codes in the format string. Sscanf works the same way as Sscan, except we must pass a format string as the second argument.

Convert string to int using strconv.ParseInt()

Golang ParseInt() method interprets the string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns a corresponding value i. See the following syntax.

func ParseInt(s string, base int, bitSize int) (i int64, err error)

If the base == 0, the base is implied by a string’s prefix: base 2 for “0b”, base 8 for “0” or “0o”, base 16 for “0x”, and base 10 otherwise.

Also, for the base == 0 only, underscore characters are allowed per the Go integer literal syntax. If the base is below 0, is 1, or is above 36, an error is returned.

The bitSize argument defines an integer type that the result must fit into.

The Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. If bitSize is below 0 or above 64, an error will be thrown.

The errors that ParseInt returns have particular type *NumError and include err.Num = s.

If the s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by the signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

See the following code example.

// hello.go

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {

	fmt.Println("\nConvert String into Integer Data type")
	str3 := "AppDividend"
	fmt.Println("Before String Value: ", str3)
	fmt.Println("Before converting Datatype:", reflect.TypeOf(str3))
	intStr, _ := strconv.ParseInt(str3, 10, 64)
	fmt.Println("After Integer Value: ", intStr)
	fmt.Println("After converting Datatype:", reflect.TypeOf(intStr))
}

Output

go run hello.go

Convert String into Integer Data type
Before String Value:  AppDividend
Before converting Datatype: string
After Integer Value:  0
After converting Datatype: int64

Here, we get output 0 because the string is built upon characters and not signed integers, but its data type is changed from string to int64. We have used Golang ParseInt() function to convert string to an integer. We have used the reflection to get the datatype of the variables using reflect.TypeOf() function.

Reflection in computing is the capacity of the program to study its structure, especially through types; it’s a form of metaprogramming. The reflection forms on the type system.

func TypeOf(i interface{}) Type

The TypeOf() returns a reflection Type that represents the dynamic type of i. If i is the nil interface value, TypeOf returns nil.

Let’s take another example. See the below code.

// hello.go

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {

	fmt.Println("\nConvert String into Integer Data type")
	str3 := "11192146"
	fmt.Println("Before String Value: ", str3)
	fmt.Println("Before converting Datatype:", reflect.TypeOf(str3))
	intStr, _ := strconv.ParseInt(str3, 10, 64)
	fmt.Println("After Integer Value: ", intStr)
	fmt.Println("After converting Datatype:", reflect.TypeOf(intStr))
}

Output

go run hello.go

Convert String into Integer Data type
Before String Value:  11192146
Before converting Datatype: string
After Integer Value:  11192146
After converting Datatype: int64

Conclusion

Golang string is the sequence of one or more characters (letters, numbers, or symbols). Strings are the most used form of data in computer programs, and you may need to convert the strings to numbers or numbers to strings reasonably often, especially when you are taking in user-generated data.

Strings can be converted to numbers by using a Golang inbuilt strconv package in the Go standard library. The strconv package has functions for converting both integer and float number types. This is a pervasive operation when accepting input from the user.

We have seen three methods that can convert Go string to int.

  1. ParseInt()
  2. Atoi()
  3. Sscanf()

If your string does not have decimal places, you’ll most likely want to convert it to an integer by using the strconv.Atoi function. But you can always go for Sscanf() function for complex scenarios.

Finally, How To Convert Golang String To Number Example Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.