Convert string to integer/ float in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

In order to convert a string to an integer or a float, the .toInt() and .toFloat() functions can be used. Of course, the string should actually correspond to the integer or floating-point value. For instance, "1.87" can be converted to float. But it doesn't make sense to convert "Hello" to float. The below example code illustrates the conversions −


void setup() {
   // put your setup code here, to run once:
   String s1 = "235";
   String s2 = "1.56";
   String s3 = "Hello";
   int i1 = s1.toInt();
   int i2 = s2.toInt();
   int i3 = s3.toInt();
   float f1 = s2.toFloat();
   float f2 = s3.toFloat();
void loop() {
   // put your main code here, to run repeatedly:

The Serial Monitor output is shown below −


As you can see, the integer and float conversions for "Hello" are 0. The conversion of floating point to integer happens through chopping, as can be seen. The integer value of 1.56 was printed as 1.

Published on 24-Mar-2021 09:51:14