Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from string to int (and throw error if unsuccessful)

Tags:

go

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 :)

like image 998
Alexander Bauer Avatar asked Oct 04 '12 23:10

Alexander Bauer


People also ask

What happens if you convert a string to int?

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.

What happens if you parseInt a string Java?

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.

Which of the following method can be used for converting a string value into int?

The method generally used to convert String to Integer in Java is parseInt() of String class.

How do you check if a string can be converted to int Python?

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.


2 Answers

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"))
}
like image 83
peterSO Avatar answered Nov 15 '22 09:11

peterSO


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)
}
like image 21
dskinner Avatar answered Nov 15 '22 10:11

dskinner