{

GoLang Examples - Convert String to Int types with examples


This article talks about three ways to convert String to Integer in Go Language.

golang convert String to int example

Golang String int datatypes

String and Int are different data types and hold different values.

When we want to perform mathematical calculations on strings that contain numbers, we must convert string to int.

if a user enters a numeric value in the text box of a web application form, this will be received as input as a string.

For example, a string contains the numbers 134 and needs this value to convert to int.

The string is a primitive type that contains a group of characters enclosed in open and close braces({ and }).

int is a primitive type that contains numeric values.

In Go language, There are different integer types - Int8, Int16, Int32. Int is a generic type that can accommodate values based on the platform Operating System.

You can check other posts on Convert Int to String.

How to Convert String to Int in Go Language?

There are 3 ways to convert a string to an Integer type in the Go language.

The following are the ways

  • strconv Atoi() function
  • strconv ParseInt() function
  • sprintf format example

strconv ParseInt function example

strconv.parseInt() the function takes a string parameter and returned an integer value

You can check my previous post on parseInt function example
Here is the syntax of a parseInt function

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

Parameters to this function
string - actual string to convert to an int value
base - base value from 2 to 36.
bitSize - This parameter reduces the size of parsed int

Return values from this function
successful conversion - default int64 type value and err=nil is returned

The error occurs conversion - int64 value zero is returned an error is returned with NumError type.

This function accepts a string parameter, converts it into a corresponding int type based on a base parameter.

By default, it returns the Int64 value

Here is an example for converting String to an int.

The string contains numerical values hexadecimal, octal, and any other numbers

func main() {  
 // bitSize argument example usage  
 fmt.Println(" ======================= bitSize argument example ======================= ")  
 v1, err := strconv.ParseInt("5612", 0, 2)  
 fmt.Println(v1, err, reflect.TypeOf(v1))  
 v2, err := strconv.ParseInt("5612", 0, 8)  
 fmt.Println(v2, err, reflect.TypeOf(v2))  
 v3, err := strconv.ParseInt("5612", 0, 16)  
 fmt.Println(v3, err, reflect.TypeOf(v3))  
 // base argument example usage  
 fmt.Println(" ======================= base argument example ======================= ")  
 v4, err := strconv.ParseInt("5612", 0, 16)  
 fmt.Println(v4, err, reflect.TypeOf(v4))  
 v5, err := strconv.ParseInt("5612", 8, 32)  
 fmt.Println(v5, err, reflect.TypeOf(v5))  
 v6, err := strconv.ParseInt("5612", 16, 64)  
 fmt.Println(v6, err, reflect.TypeOf(v6))  
 // String Argument argument example usage  
 fmt.Println(" ======================= String argument example ======================= ")  
 v7, err := strconv.ParseInt("0x123", 0, 64) // hexdecimal Numeric Conversion  
 fmt.Println(v7, err, reflect.TypeOf(v7))  
 v8, err := strconv.ParseInt("0123", 0, 64) // Octal Number Conversion  
 fmt.Println(v8, err, reflect.TypeOf(v8))  
 v9, err := strconv.ParseInt("123", 0, 64) // any other number  
 fmt.Println(v9, err, reflect.TypeOf(v9))  
 // Invalid String argument conversion example usage  
 fmt.Println(" ======================= Invalid String argument conversion example usage ======================= ")  
 v10, err := strconv.ParseInt("abc", 0, 64) // any other number  
 fmt.Println(v9, err, reflect.TypeOf(v10))  
}  

The output of the above program is

======================= bitSize argument example =======================  
1 strconv.ParseInt: parsing "5612": value out of range int64  
127 strconv.ParseInt: parsing "5612": value out of range int64  
5612 <nil> int64  
 ======================= base argument example =======================  
5612 <nil> int64  
2954 <nil> int64  
22034 <nil> int64  
 ======================= String argument example =======================  
291 <nil> int64  
83 <nil> int64  
123 <nil> int64  
 ======================= Invalid String argument conversion example usage =======================  
123 strconv.ParseInt: parsing "abc": invalid syntax int64  

strconv.Atoi function example

strconv.Atoi() function takes a string and returns the integer type value

Here is function signature of strconv.Atoi() function

func Atoi(s string) (int, error) 

Parameters: It accepts a string as a parameter.

returns: if the string value is converted to int successfully, It returns the int value and error as a nil value.

if an error occurs, int value is zero, error is nil returned.

For example, if 123 value is passed to atoi() function, It returns int value -123 and error is nil.

if asdfadsf is passed, returned int value is zero, and the following error is returned at runtime.

strconv.Atoi: parsing “asdfadsf”: invalid syntax This function is equivalent to ParseInt(s, 10, 0) which converted of type int

package main  
  
import (  
 "fmt"  
 "strconv"  
)  
  
func convertStringToInt(str string) {  
 strValue, err := strconv.Atoi(str)  
 if err == nil {  
  fmt.Printf("DataType: %T  \n", strValue) // Display DataType  
  fmt.Println("value - ", strValue)        // variable value  
 }  
 fmt.Println("error - ", err)  
  
}  
func main() {  
 convertStringToInt("243")  
 convertStringToInt("asdfadsf")  
}  

When the above program is compiled and executed, the return output is as follows

DataType: int  
value -  243  
error -    
error -  strconv.Atoi: parsing "asdfadsf": invalid syntax  

fmtcan function example

fmt package provides the sscan() function which scans string arguments and stores them into variables.

This function reads the string with spaces and assigns it into consecutive Integer variables.

The below program has three variations.

  • convertStringToInt() function read normal string which contains numeric values converted to integer
  • customConversion() which contain strings in the string separated by hyphen.
  • customConversionWithSpaces() which contains numbers separated by spaces in a string
package main  
  
import (  
 "fmt"  
)  
  
func convertStringToInt(str string) {  
 intValue := 0  
 _, err := fmt.Sscan(str, &intValue)  
 fmt.Println(err)  
 if err == nil {  
  fmt.Printf("value=%d, type: %T\n", intValue, intValue)  
 }  
}  
func main() {  
 convertStringToInt("123")           // 123 is returned of int type  
 convertStringToInt("1aa23a")        // 1 is returned of int type  
 convertStringToInt("abcc")          // It gives error - expected integer  
 customConversion("number=00178")    // 00178  
 customConversionWithSpaces("1 3 5") // 1 3 5 is output  
}  
  
//custom format  
func customConversion(str string) {  
 var intValue int  
 if _, err := fmt.Sscanf(str, "number=%5d", &intValue); err == nil {  
  fmt.Printf("value=%d, type: %T\n", intValue, intValue)  
 }  
}  
  
//custom string contains spaces  
func customConversionWithSpaces(str string) {  
 var m, n, o int  
 fmt.Sscan(str, &m, &n, &o)  
 fmt.Println(m, n, o)  
}  
  

The output of the above program is

<nil>  
value=123, type: int  
<nil>  
value=1, type: int  
expected integer  
value=178, type: int  
1 3 5  

Which one is better in Performance time taken?
Benchmark was calculated to find out the time taken for the string to int conversion. parseInt() is best in performance, Next is atoi()function, least in performance is sscan() function.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.