How to Convert Golang String to Int

0
492
How To Convert Golang String To Int

Go is statically typed. Every variable has a static type, precisely one type known and fixed at compile time: int, float32, *MyType, []byte, and so on.

In Go, data types distinguish one specific kind of data, defining the values you can assign to a type and the operations you can execute.

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.

Golang String to Int

To convert a string to int in Golang,

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

Golang has a built-in package called strconv that provides functions that convert string to int.

The Atoi() Sscanf(), and ParseInt() are three functions that convert Golang string to int. Go is a statically typed language; data types are bound to variables rather than values.

That means 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.

Converting Golang string to int with strconv.Atoi(str)

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

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

// 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 used Atoi() function to convert a string to an integer.

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

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

In the above code example, we have taken an integer 11 and made it a 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” Golan”” 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)
	}
}

Our data is “Golang,” a string in the above code.

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 dive deep into Golang fmt.Sscanf() function.

Golang func Sscanf()

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

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

// 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:0021” where you have the prefix “id”, and the number is fixed at five 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 Scan, except we must pass a format string as the second argument.

Converting 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 a 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 a string to an integer. We have used reflection to get the data type of the variables using reflect.TypeOf() function.

Reflection in computing is the program’s capacity to study its structure, mainly 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 representing 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. Therefore, 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 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.

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

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

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