# Convert String to Integer

How can I convert a string to integer?

I have a string that contains a set of values, some are text, but some are actually numeric values, all separated by commas. I can use split(string,",") to get any particular value, but can’t seem to find the way to convert that value if it’s numeric.

New to Processing, so perhaps I just didn’t find it in the Reference section.

Thanks for any help.

1 Like
1 Like

So I made a little sketch to show you what I think it is you are asking about:

``````String word, number;

void setup()
{
size(100,100);
}

void draw()
{
word = "hello";
number = "123";
mixed = "hello123";

//next two lines will not work, you will get a NumberFormat Exception
System.out.println("Let's try to convert this string that is only words to an int: "+Integer.valueOf(word));
System.out.println("Let's try to convert this string that is both  to an int: "+Integer.valueOf(mixed));
//This will work
System.out.println("Let's try to convert this string that is only numbers to an int: "+Integer.valueOf(number));

}
``````

These lines of code will not work:

`System.out.println("Let's try to convert this string that is only words to an int: "+Integer.valueOf(word));`

`System.out.println("Let's try to convert this string that is only words to an int: "+Integer.valueOf(mixed));`

Because the variables word and mixed contain letters, they will not be converted to ints. But because number is a pure number of 123, it will be converted to an int. Furthermore, you can make a new int, and set it like this:

`int newNumber = Integer.valueOf(number);`

Hopefully this helps,

EnhancedLoop7

Integer.valueOf(some-string) works perfectly and sublimely easy.

Fabulous, thanks.

But one additional question: where is this in the Processing.org Reference page(s)? I feel like I’m missing a lot of Processing features/functions/methods.

Sorry, but I don’t think that reference is the answer.
See EnhancedLoop7’s response to this question, which does solve it.

Thanks, though, for responding.

Actually, @GoToLoop answer is both correct and better. `int(someString)` gets turned into `parseInt(someString)`. I would use the latter personally, as you’ll get less confused by normal Java code later. `parseInt` calls `Integer.parseInt` which is what you want here. `Integer.valueOf` returns an Integer not an int.

3 Likes

@jarlook I personally don’t know too much about int(someString) but you learn something new everyday I guess! After looking at the reference in Processing I do see that int(someString) in fact is code native to the Processing language that works as well! From what I believe though, all three:

``````int(someString); //this is the best for Processing
Integer.valueOf(someString); //this is more Java related, and as @neilcsmith said, will return an Integer object
Integer.parseInt(someString); //also Java related, but returns an actual primitive int object
``````

So really in the end of the day, it just depends on what it is you specifically need. All three should somehow get you in the ballpark of your expected result. Hope that helps,

EnhancedLoop7

3 Likes

parseInt is also part of the Processing API.

1 Like

I had same issue as original poster. I am sending to Processing both a variety of Sensor values to be used by Objects like meter, or Text to display on the canvas. I am also ending simple Arduino debug messages that can be displayed in the console that are not used by any Processing object. So that my Processing code can distinguish these apart and filter the data to be sent to the various canvas objects I will add identifying characters in front of the sensor data. For example a sensor value meant for meter object m1 may have appended in front of the value “v1m*”, so the arduino would send via Serial.println(“v1m123”); if the value where say 123. Then using the various string functions parse out the integer data and assign the int() value of that to the meter instance m1.
I am sure there is a more elegant way to do this but this is what I have come up with.

In order to get the int() function to work I had to remove 2 characters from the received data and I do not understand why when I expected it to be only one.

import processing.serial.;
import meter.
;

Meter m;
int sensorValue;

Serial myPort; // The serial port
int whichKey = -1; // Variable to hold keystoke values
int inByte = -1; // Incoming serial data
String debugMsg;
String deviceData;
String astr = “*”;

void setup() {
size(800, 600);
m = new Meter(this, 50, 175, false);
m.setUp(0, 212, 0.0, 212.0, 180.0, 360.0);
String[] scaleLabels = {“0”, “20”, “40”, “60”, “80”, “100”, “120”, “140”, “160”, “180”, “200”, “220”};
m.setScaleLabels(scaleLabels);
m.setDisplayDigitalMeterValue(true);
m.setTitleFontColor(color(0, 0, 255));
m.setTitle(“Temperature”);

// create a font with the third font available to the system:
PFont myFont = createFont(PFont.list()[2], 14);
textFont(myFont);

// List all the available serial ports:
printArray(Serial.list());

String portName = Serial.list()[Serial.list().length - 1];
myPort = new Serial(this, portName, 57600);
myPort.clear();
myPort.bufferUntil(’\n’); //Sets # bytes to buffer before calling serialEvent()
}

void draw() {

background(55);
//text("Debug: " + debugMsg, 10, 160);
text("Last Sent: " + (char)whichKey, 10, 100);
// Input for testing.

// Update the sensor value to the meter.
m.updateMeter(sensorValue);
// Use a delay to see the changes.
delay(700);
}

void serialEvent(Serial myPort) {
String delim = “v1m”;
int l1;

``````if(myPort.available() > 0) {
//println(deviceData);
//The * must be the first char in the received String so we know we have a string meant for
//Processing, otherwise it is a debug
//statement to just display in the console or in a TEXT object.
if(deviceData.indexOf(delim) == 0) {
l1 = deviceData.length();
Adata = deviceData.substring(3, l1-2); //Extract only the numerical values, I do not know why I
//have to subtract 2 characters from the length instead of just 1 in order to get int() to work?????
println(sensorValue);
}
else
{
debugMsg = deviceData;
print(debugMsg);
}
}
``````

//sendData(“Sending data to host\n”);
}

void keyPressed() {
// Send the keystroke out:
myPort.write(key);
whichKey = key;
myPort.write(’\n’);
//delay(5000);
}

void sendData(String Sdata) {

myPort.write(Sdata);

}

Hello,

Take a look here:

https://processing.org/reference/trim_.html

`:)`

Yeah, sometimes there is a line feed at the end of the data.

trim() helps.

Hey, and welcome to the forum!

Great to have you here!

Hello,

https://discourse.processing.org/faq#format-your-code

I used simulated data here and only had to remove 1 character which was the line feed ( ‘\n’).

I may be going off topic here.
Start another one if you want to continue this.

Please provide a small snippet of the Arduino code and please format properly for the forum.

Some test code without the Arduino sending:

Test Code
``````String s;

void setup()
{
//s = "v1m1v1m2v1m3v1m4/n";
char LF = '\n';    // 1 character
//Serial.println(“v1m123”);
s = "v1m123" + LF; // 6 characters + 1 character for LF (line feed)
testData(s);
}

void testData (String s)
{
String delim = "v1m";
int l1;

//String deviceData = trim(s);
String deviceData = s;

if(deviceData.indexOf(delim) == 0)
{
l1 = deviceData.length();

String Adata = deviceData.substring(3, l1-1); //-1 for LF
//Extract only the numerical values, I do not know why I
//have to subtract 2 characters from the length instead of just 1 in order to get int() to work?????
println(sensorValue);
}
else
{
String debugMsg = deviceData;
print(debugMsg);
}
}
``````

Here is another topic that may be of interest:

Serial plotter over bluetooth

Arduino can send data that is comma delimited (or other delimiter) and terminated with a line feed (or other terminator) and Processing can receive and split it.

`:)`