round() function rounds off .5 values

• Hey,
I wrote this code:

void InputNodeInstance::changeSize(QString side, float mult){
double newWidth = width * mult;
width = round(newWidth);
double newHeight = height * mult;
height = round(newHeight);
qDebug() << "newWidth:" << newWidth;
qDebug() << "width: " << width;
}

When I call the function with 0.9 as mult, I get this output:

newWidth: 49.5
width:  49

When I add this line to the code:

qDebug() << round(newWidth);

it outputs 49. Why does round() function round 49.5 to 49 !?

• Hi
because that is how it works?
http://www.cplusplus.com/reference/cmath/round/

Sorry should be 50 :) according to example.

So that i dont know :)

qDebug() << round(5.5); shows 6
qDebug() << round(49.5); show 50

const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
printf (format, 5.5,round( 5.5),floor( 5.5),ceil( 5.5),trunc( 5.5));
does as expected.
5.5 6.0 5.0 6.0 5.0

• @mrjj
Hm, but as you can see, here it rounds 49.5 to 49...
I don't understand that.
And it gets even weirder: when I do

qDebug() << width * mult + 0.5;
width = width * mult + 0.5;
qDebug() << width;

it outputs
50
49
???

• Hi,
following this thread I would assume it is float to double conversion that you can blame. Would it be possible for you to (just for the test) use one single type throughout the code to check if problem persists?

• @artwaw
Yes, I changed it to double in the parameter list and now, I get 50... ok.... I want to understand that... How is this possible...
Now, that's completely blowing my mind
Really big thank you, I would not have thought, this is a problem

• @Niagarer My pleasure to help.