Are there functions available for the Arduino to round or truncate floating point (real) values?
Just add 0.5 and cast to an int:
float f = 2.345f;
float f2 = 2.845f;
int rounded = (int)(f+0.5f); // roundedĀ == 2
rounded = (int)(f2+0.5f); // roundedĀ == 3
I am familiar with type casting to int and the inherent rounding to the whole number. I need more flexibility and functionality than round to a whole numbet. I need to round or truncate floating point values., ie round 2.56 to 2.6.
(At least in IDE version 1.6.5) there is a built in round() function. Use that with a pre and post multiplication by a power of 10.
Serial.println(round(1.550 * 10) / 10.0);
Serial.println(round(1.499 * 10) / 10.0);
Serial.println(round(-1.499 * 10) / 10.0);
Serial.println(round(-1.550 * 10) / 10.0);
... prints ...
1.60
1.50
-1.50
-1.60
Was about to suggest something along those lines, only issue is, the multiplication and division gives you the decimal place accuracy, so might be worth sticking it in a function that works out the multipliers based on the desired d.p
There are functions round(), floor() and ceil(), depending what you want to do.
guix:
There are functions round(), floor() and ceil(), depending what you want to do.
Is there a help link for them?
They are standard C++ functions. This page is about round and has links to the others.
There are functions round(), floor() and ceil(), depending what you want to do.
These won't help on their own, he stated he wants to round to a set decimal place, not just the integer part.
You'll need something along these lines:
float round_to_dp( float in_value, int decimal_place )
{
float multiplier = powf( 10.0f, decimal_place );
in_value = roundf( in_value * multiplier ) / multiplier;
return in_value;
}
Sorry, I missed this part ![]()