C++ Rounding

Hey Guys,

I need some help with rounding in c++. So I have a game script (the two player chip game) and it runs like a beauty, but for some reason my rounding system is off. I have my script so that the formula:

chipvalue = (chips/2);

For some reason if the chips are: 125 then when it divides by 2 the value is 62 instead of rounding up to 63. I have tried ceil but it did not work.

The variable chipvalue is an integer.

Any suggestions?
If both arguments used in division are integers the result will also be an integer. To get a floating point value you can change the integer 2 into the double 2.0. To do rounding you can use std::round in <cmath>.
chipvalue = std::round(chips/2.0);
Last edited on
When doing an integer division in c++, the result will always be rounded down, so your rounding system isn't off :)

For example even if you divide 1999 by 1000, the result will be 1 if both 1999 and 1000 are integers.

If you want the resulting values to be rounded correctly, calculate the result of integer division z = x/y, then multipliy z with y and subtract this result from x. If this value is greater than or equal to y/2, you have to add one to z.

There are probably more efficient or robust solutions to this problem, but this workaround should work nicely.
My previous answer might not actually give the result you expect because not all floating point values can be represented exactly leading to rounding errors. In this case when dividing by two you can avoid using floating point numbers by using % instead (assuming chips > 0).
chipvalue = (chips/2) + (chips%2);
Thanks guys! It works!

Case solved :)
Topic archived. No new replies allowed.