I want to convert string to integer in golang. But I don't know the format of string. For example, "10"
-> 10
, "65.0"
-> 65
, "xx"
-> 0
, "11xx" -> 11, "xx11"->0
I do some searching and find strconv.ParseInt()
. But it can not handle "65.0"
. So I have to check string's format.
Is there a better way?
Atoi() The Atoi() function is an inbuilt function of the strconv package which is used to convert (interpret) a given string s in the given base (10) and bit size (0) and returns the corresponding integer value. The Atoi() function is equivalent to ParseInt(s, 10, 0), converted to type int.
Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn't support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.
int64 is a version of int that only stores signed numeric values composed of up to 64 bits. So, for example, if you try to store a string value in it, or an integer beyond what can be made using 64 bits, the program would return an error or result in an integer overflow.
I believe function you are looking for is
strconv.ParseFloat()
see example here
But return type of this function is float64.
If you don't need fractional part of the number passed as the string following function would do the job:
func StrToInt(str string) (int, error) {
nonFractionalPart := strings.Split(str, ".")
return strconv.Atoi(nonFractionalPart[0])
}
You can use these three functions to convert a string value to an integer or a float.
Note: the strconv
builtin package must be imported to execute these functions.
func Atoi(s string) (int, error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseFloat(s string, bitSize int) (float64, error)
package main
import (
"fmt"
"strconv"
)
func main() {
i, _ := strconv.Atoi("-42")
fmt.Println(i)
j,_ := strconv.ParseInt("-42", 10, 8)
fmt.Println(j)
k,_ := strconv.ParseFloat("-42.8", 8)
fmt.Println(k)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With