I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00
How do to do this?
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityI am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00
How do to do this?
It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.
For example:
1.34 *2 = 2.68
round(2.68) = 3
3 /2 = 1.5
and
32.78 *2 = 65.56
round(65.56)= 66
66 /2 = 33
I made a little algorithm from the first thing that popped into my mind. I'm using integers, since I believe it works better as floats.
For example, you can represent euro's (with floating points) by expressing them in cents.
unsigned int roundToFifty(unsigned int nonRound){
unsigned int rest = nonRound % 50;
unsigned int fits = floor(nonRound / 50);
unsigned int add = 0;
if(rest >= 25){
if(rest >= 75){
add = 100
}else{
add = 50
}
}
return fits*50+add
}
I actually think the algorithm is a tad weird and something simpler/more effective could also exist. It was just the first thing that popped into my mind.
float i=1.5237475984328953;
#include "math.h"
void setup()
{
Serial.begin(9600);
}
void loop() {
Serial.println(i,6);
float price = i*1000;
Serial.println(price,2);
float roundNearest = roundf(i*1000) ; // x 100 for two decimal place
roundNearest = roundNearest/1000;
Serial.println(roundNearest,6);
price = (roundNearest*1000);
Serial.println(price,2);
while(1){}
}
you u can use roundf() like in this video Demo Video