How to Round A Float Number to The Nearest Integer in Arduino

Ammar Ali Feb 02, 2024
How to Round A Float Number to The Nearest Integer in Arduino

In this tutorial, we will discuss how to round a float to an int using the round() function.

Round a float to Nearest int Using the round() Function

The round() function rounds a float number to nearest int. This function takes a variable of type float as an input and returns a variable of type int. If the input variable’s decimal value is less than .5, the return int value will be less than the input variable; otherwise, the return int value will be greater than that of the input variable. For example, see the below code.

void loop() {
  float myFloat = 5.4;
  int myInt = round(myFloat);
}

In the above code, the float variable will be converted to 5 since the decimal value is less than .5. See another example.

void loop() {
  float myFloat = 5.6;
  int myInt = round(myFloat);
}

In the above code, the float variable will be converted to 6 since the decimal value is greater than 0.5. When the decimal value is exactly equal to 0.5, it will also be converted into 6. See the example below.

void loop() {
  float myFloat = 5.5;
  int myInt = round(myFloat);
}

In the above code, the float variable will be converted into 6 since the decimal value is greater than .5.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - Arduino Math