mfusco
June 30, 2025, 9:19pm
1
With the code below, the .toInt() function is not working as expected. The variable moistureLevel is empty when printing to the Serial monitor:
String str = "POST /1000";
int moistureLevel;
float moisturePercentage;
void setup() {
Serial.begin(9600);
while (!Serial);
moistureLevel = str.toInt();
moisturePercentage = (moistureLevel / 3400) * 100;
Serial.println("str: " + str);
Serial.println("level: " + moistureLevel);
Serial.println("percentage: " + String(moisturePercentage));
}
void loop() {
// put your main code here, to run repeatedly:
}
From https://docs.arduino.cc/language-reference/en/variables/data-types/stringObject/Functions/toInt/
Description
Converts a valid String to an integer. The input String should start with an integer number. If the String contains non-integer numbers, the function will stop performing the conversion.
The string strdoes not start with a valid integer number.
(Posts crossed)
mfusco
June 30, 2025, 9:26pm
4
With this code I get the same issue:
String str = "POST /1000";
String strNumbers;
int moistureLevel;
float moisturePercentage;
void setup() {
Serial.begin(9600);
while (!Serial);
strNumbers = str.substring(6);
moistureLevel = strNumbers.toInt();
Serial.println("str: " + str);
Serial.println("strNumbers: " + strNumbers);
Serial.println("level: " + moistureLevel);
Serial.println("percentage: " + String(moisturePercentage));
}
void loop() {
// put your main code here, to run repeatedly:
}
Serial.println("level: " + moistureLevel);
You cannot concatenate a String and an integer like that. You must print them separately
mfusco
June 30, 2025, 10:01pm
6
I have a follow up question which is why does moisturePercentage print 0.00 after the line of code below?
moisturePercentage = (moistureLevel / 3400);
The calculation is being done using integers. Force it to use floats by using
moisturePercentage = (moistureLevel / 3400.00);
You can also print in one line by converting the integer element to string:
Serial.println("level: " + String(moistureLevel));
Not sure which is more efficient though.
Interesting question about the division. Casting one of the operands to a float - seems not to matter which - works as well. I guess that's what adding the .00 does automatically anyway.
ec2021
June 30, 2025, 10:26pm
9
Hi @mfusco ,
if you are interested in the different ways to format strings, integers and float data you may have a look at this comprehensive webpage
https://wolles-elektronikkiste.de/en/formatted-output
Enjoy!
ec2021
kenb4
June 30, 2025, 11:19pm
10
FYI, to see what happens when you try to concatenate a C-string and an integer
for (int anInt = 0; anInt < 6; anInt++) {
Serial.println("level: " + anInt);
}
prints
level:
evel:
vel:
el:
l:
:
The literal string resolves as a pointer to its contents, a const char *. If the integer is larger than than length of the string, you're asking to print whatever is out there in memory; could be nothing, or invisible, but more likely something.