Convert variables from one type to another in Arduino


In order to convert variables from one type to another, you use the CAST operator. The syntax is −

(type) var;

Where var is the variable to be casted, and type is the new type to which you wish to convert it. For example, if you have a variable of type float, and wish to cast it as an int.

Example

Here’s how you can do it −

float f;
int i;

void setup() {
   // put your setup code here, to run once:
   f = 5.6;
   i = (int) f;
   Serial.println(f);
   Serial.println(i);
}

void loop() {
   // put your main code here, to run repeatedly:
}

The Serial Monitor will print 5.6 followed by 5 (and not 6). This is because casting a float to int truncates the float, doesn’t round it.

Updated on: 31-Jul-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements