String conversion

How do I convert a string (containing numbers) to an integer?

str.tointeger() should work just fine.

thanks, I was looking for something like this.

string.tointeger() is not working for me if the string has any non-numeric characters.
I get an error “cannot convert the string” in the log.
This is Agent side code.
If the string is simple such as “3” then it works as expected.
But if the string is “x” I get the error.

That sounds like expected behavior. You can always use try/catch to catch these errors yourself without crashing the program?

Yup, I am using try/catch. I’m just not used to having to use try/catch for basic type conversion.

In this particular case I am getting a JSON object and the value “3” comes across as a string “3”. I am then forwarding to web service. It requires a float as the value in a JSON object.

I am going to use this as an argument to ubidots that they should be more accepting the type of the value they receive.

As in, ubidots want 3.0 vs 3?

as in, ubidots won’t accept “3”

More specifically uibdots wants {value: 3} or {value: 3.0} but won’t take {value: “3”}

I’m getting this when clearly passing a string.

local buffer = “”;

function arduinoData() {
local b =;
if (b == 13) {
server.log(buffer.tointeger());// <— PROBLEM LINE
buffer = “”;
} else {
if (b != 10) {
buffer += b.tochar();

Server.log(buffer) outputs “3193” and the like. Server.log(buffer.tointeger()) gets me:
“ERROR: cannot convert the string”

My guess is that you have something else in the buffer non-printable which is causing problems.

Dump the string in hex with:

local dump = "hex: "; for(a in buffer) dump+=format("%02x ",a); server.log(dump);

…and see what else is hiding in there.