212x Filetype PDF File size 0.08 MB Source: www.tutorialkart.com
Golang – Convert String to Integer String to Integer in Golang To convert String to Integer in Golang, use Atoi() function of strconv package. The usage of Atoi() function is // import statement import "strconv" // convert string to integer number, error = strconv.Atoi("14") where strconv.Atoi() takes string as argument and converts into an integer. The function also returns an error. error object will be null if there is no error. Atoi means A(Alphabets or String) to i(integer). Example 1 – Convert String to Integer In this example, we will take a string that has only a number and convert it to integer value. example.go package main import "fmt" import "strconv" func main() { var str = "14" // convert string to integer number, error := strconv.Atoi(str) fmt.Println("error:", error) fmt.Println("number:", number) } Output error:number: 14 Example 2 – Convert String to Integer [Negative Scenario] In this example, we will take a string that has also non-numeric characters. We will try converting it to a number. We should get an error. example.go package main import "fmt" import "strconv" func main() { var str = "14sup." // convert string to integer number, error := strconv.Atoi(str) fmt.Println("error:", error) fmt.Println("number:", number) } Output error: strconv.Atoi: parsing "14sup.": invalid syntax number: 0 We received a “invalid syntax” error while trying to parse a string that contains non-numeric characters. Golang ✦ Golang Tutorial ✦ Run Golang Program ✦ Golang If Else ✦ Golang Switch ✦ Golang For Loop ✦ Golang Comments ✦ Golang Functions ✦ Golang Array ✦ Golang Slice ✦ Golang Struct ✦ Golang Class ✦ Golang Range ✦ Golang Map ✦ Golang Goroutine ✦ Golang Channel Golang String Operations ✦ Golang String Length ✦ Golang String Concatenation ✦ Golang Split String ✦ Golang String - Get Index of Substr ✦ Golang String to Uppercase ✦ Golang String to Lowercase ➩➩ Golang Convert String to Integer
no reviews yet
Please Login to review.