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.


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;

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.