 # Custom round function for floats

Hello,

I've been trying to create a function myself without any luck.

I need to round floating values that looks like this "12.45" for example. Two numbers before and after the dot.

Normal round function rounds up at number being 5. I need it to round up at 6 and if below 6 it should round down instead.

Example:
12.45 = round down to 12.40 and remove the 0 which makes it return 12.4.
12.46 = round up to 12.50 and remove the 0 which makes it return 12.5.+

## float value = 12.46; value = roundFunction("12.46"); Serial.print(value);

I've searched the forums and found a few round functions alltho none of them have the magic breaking point at 6 that I need, they all round at 5 which is standard.

Appreciate any assistance!

you could try multiplying by 10, rounding (add 0.49), take int() and the divide by 10

Just subtract 1 at the digit that should be rounded (in your case 0.01) and then use the standard rounding function.

12.40 - 0.01 = 12.39 -> 12.40
12.41 - 0.01 = 12.40 -> 12.40
12.42 - 0.01 = 12.41 -> 12.40
12.43 - 0.01 = 12.42 -> 12.40
12.44 - 0.01 = 12.43 -> 12.40
12.45 - 0.01 = 12.44 -> 12.40

12.46 - 0.01 = 12.45 -> 12.50
12.47 - 0.01 = 12.46 -> 12.50
12.48 - 0.01 = 12.47 -> 12.50
12.49 - 0.01 = 12.48 -> 12.50
12.50 - 0.01 = 12.49 -> 12.50

Thanks for those two replies. Trying to get my head around it. Math is my weekest part, I'm sorry but I dont quite understand how I can make the into a function.

Just call the round() function and subtract 0.01 inside the call or before if that is more convenient.

y = round( x - 0.01 );

float myRound( float x )
{
return round( x - 0.01 );
}

then call

y = myRound( z );

That only gives 12.00, it rounds the decimal values to 00.

Alltho I found a solution, printing with only one decimal solves it. But that doesn't actually change the value itself. I only cuts away the last digit.

You are right, I was not thinking it through. You need to shift the number before and after rounding. Also note this works for positive numbers only. For negative you would need to do a separate case with if x < 0 and add 0.01.

y = round( 100 * x - 1 ) / 100;

float myRound( float x )
{
return round( 100 * x - 1 ) / 100;
}

then call

y = myRound( z );

don’t you need to truncate the fraction < 0.1. (use int() to return the integer part of a float)

Would something like this work?

``````round(x * 10) / 10
``````

(You might need to put parentheses around `round` in case Arduino is still defining a function-like macro named "round" that does something similar to but not exactly like the standard C++ "round" function.)

Edit: actually, that would probably round 12.45 up to 12.50. @gcjr's solution should work.

Klaus_K:
You are right, I was not thinking it through. You need to shift the number before and after rounding. Also note this works for positive numbers only. For negative you would need to do a separate case with if x < 0 and add 0.01.

y = round( 100 * x - 1 ) / 100;