My apologies if this is a beginner question, but I simply can't seem to find any solution for this. I'm trying to take an argument that can be either a string
or an int
, depending on the context, and I need to determine which type, (then convert it to int
if it is indeed that type.)
Thank you :)
Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.
The method generally used to convert String to Integer in Java is parseInt() of String class.
To check if a string can be converted to an integer:Wrap the call to the int() class in a try/except block. If the conversion succeeds, the try block will fully run. If the conversion to integer fails, handle the ValueError in the except block.
For example,
package main
import (
"errors"
"fmt"
"strconv"
)
func IntConv(arg interface{}) (int, error) {
switch x := arg.(type) {
case int:
return x, nil
case string:
return strconv.Atoi(x)
}
return 0, errors.New("IntConv: invalid argument ")
}
func main() {
fmt.Println(IntConv(7))
fmt.Println(IntConv("42"))
}
http://golang.org/pkg/strconv/#Atoi
func Atoi
func Atoi(s string) (i int, err error)
Atoi is shorthand for ParseInt(s, 10, 0).
This is an update. To clarify, since Atoi accepts string, then trying to pass an int
will cause a compile time error. If you need a check during runtime, then you can do something like this.
package main
import (
"fmt"
"strconv"
"errors"
)
func toInt(data interface{}) (n int, err error) {
switch t := data.(type) {
case int:
return t, nil
case string:
return strconv.Atoi(t)
default:
return 0, errors.New(fmt.Sprintf("Invalid type received: %T", t))
}
panic("unreachable!")
}
func main() {
var (
n int
err error
)
n, _ = toInt("1")
fmt.Println(n)
n, _ = toInt(2)
fmt.Println(n)
n, err = toInt(32.3)
fmt.Println(err)
}
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