Golang convert string to int – example

In Golang, you can convert string to int type using the following functions. strconv.ParseInt(s, base, bitSize) strconv.Atoi(s) Let’s checkout the example of above functions: 1….

The post Golang convert string to int – example appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Deven

In Golang, you can convert string to int type using the following functions.

  1. strconv.ParseInt(s, base, bitSize)
  2. strconv.Atoi(s)

Let’s checkout the example of above functions:

1. Golang convert string to int using strconv.ParseInt(s, base, bitSize)

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1111"

	n, err := strconv.ParseInt(str, 2, 32)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(n)
	}
}

The strconv.ParseInt(s, base, bitSize) converts the given string to an integer in the given base (0, 2 to 36) and bit size (0 to 64). The output of the above code will be 15 .

2 Golang convert string to int using strconv.Atoi(s) method

package main

import (  
    "fmt"
    "strconv"
)

func main() {  
    str := "3"

    n, _ := strconv.Atoi(str)
    fmt.Println(n)
}

we use strconv.Atoi(s) to convert a string s to a 32 bit integer. The output of the above code will be 3 .

The post Golang convert string to int – example appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Deven


Print Share Comment Cite Upload Translate Updates
APA

Deven | Sciencx (2021-02-07T17:01:26+00:00) Golang convert string to int – example. Retrieved from https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/

MLA
" » Golang convert string to int – example." Deven | Sciencx - Sunday February 7, 2021, https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/
HARVARD
Deven | Sciencx Sunday February 7, 2021 » Golang convert string to int – example., viewed ,<https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/>
VANCOUVER
Deven | Sciencx - » Golang convert string to int – example. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/
CHICAGO
" » Golang convert string to int – example." Deven | Sciencx - Accessed . https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/
IEEE
" » Golang convert string to int – example." Deven | Sciencx [Online]. Available: https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/. [Accessed: ]
rf:citation
» Golang convert string to int – example | Deven | Sciencx | https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.