Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an elegant way to parse an Integer

Tags:

go

Right now I am doing the following in order to parse an integer from a string and then convert it to int type:

tmpValue, _ := strconv.ParseInt(str, 10, 64) //returns int64
finalValue = int(tmpValue)

It is quite verbose, and definitely not pretty, since I haven't found a way to do the conversion in the ParseInt call. Is there a nicer way to do that?

like image 697
Sergi Mansilla Avatar asked Dec 16 '12 13:12

Sergi Mansilla


People also ask

What is parse int in C?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

It seems that the function strconv.Atoi does what you want, except that it works regardless of the bit size of int (your code seems to assume it's 64 bits wide).

like image 109
Fred Foo Avatar answered Oct 06 '22 15:10

Fred Foo


If you have to write that once in your program than I see no problem. If you need at several places you can write a simple specialization wrapper, for example:

func parseInt(s string) (int, error) {
        i, err := strconv.ParseInt(str, 10, 32)  // or 64 on 64bit tip
        return int(i), err
}

The standard library doesn't aim to supply (bloated) APIs for every possible numeric type and/or their combinations.

like image 25
zzzz Avatar answered Oct 06 '22 16:10

zzzz