# String to int

Hello all,

I'm working on a project and can't seem to convert string to int. i've tried function atoi but it did not work with me in the following manner:

int x = atoi(str);

So I decided to code my own function and this is what I came up with :

int stoi(String str)
{
int value = 0;
for (int i = 0 ; i < str.length(); i++)
{

int x = str.charAt((str.length() - i - 1)) - '0';

value = value + x * (int)pow(10, i);

}
return value;
}

However, for some reason sometimes it does not work with numbers larger than 2 digits.

I've tried to remove the cast from float ( coming from the pow method ) to int, but it did not change anything. The weird thing is that sometimes when the string is for example 2014. The outcome is 2012. Sometimes it's something like 4567 and the outcome is 4564. I don't know thy it's acting that way. I debugged it all night long and couldn't find an answer to this.

Can somebody explain the behavior. If not, then can somebody give me a way to turn strings to integers and doubles?

One way I convert a string like 1500 to a number for use for servo control.

if (readString.length() >0) {
Serial.println(readString);  //so you can see the captured string
myservo.writeMicroseconds(readString.toInt()); //convert readString to number for servo
readString=""; //empty for next input
}

What have you got against the String;:toInt() function?

value = value + x * (int)pow(10, i);

Oh, yeah, use a float function to (try to) produce integer results. Not too surprising that that doesn't work.

There are two much simpler ways. First:

char strVal[10];
str.toCharArray(strVal, 10);
int val = atoi(strVal);

or

int val = str.toInt();

Here's an example to convert to unsigned (because I was too lazy to deal with a possible sign character):

unsigned atou(char *s)
{  unsigned c,r = 0;
if (s)
while ((c = *s++) && (c >= '0') && (c <= '9'))
r = 10 * r + c - '0';
return r;
}

@Morris
OP does not have a char array, and does not appear to know how to get one from a String, so that code won't do much good. In addition, the atoi() function is not too lazy to deal with signed values.

@PaulIS - agreed. I wasn't providing the OP with a program solution but, rather, a nudge in the direction of an improved algorithm.

use a float function to (try to) produce integer results

Yep, that is the problem with the OP's code. Here's the output of i and "(int)pow(10,i)" for the first 5 values of i.

0  1
1  10
2  99
3  999
4  9999

That explains why the numbers were lower than expected.

Pete