1

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?

2
  • I'd suggest not even using floats. 0.5 = 50, 1.34 = 134, 32.78=3278, should make the calculations faster/more efficient.
    – Paul
    Aug 18, 2016 at 10:07
  • Also, let's say you have 134, you can do 134%50, which will return 34 and then you can check if it's above 24 (under = round to 0) and above 74 (under is round to 50) and else you round to 100.
    – Paul
    Aug 18, 2016 at 10:12

3 Answers 3

7

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
2
  • The multiply by 2 is actually very clever I already felt like such a simple way should exist.
    – Paul
    Aug 18, 2016 at 10:25
  • Commonly used for nearest 0.10 and 0.05 in cash registers, too (using 10, 20).
    – mckenzm
    Sep 28, 2017 at 19:10
0

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.

0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.