## Friday, 2 March 2012

### Rounding Numbers in C & C++

I’ve been working my way through the functions in the <math.h> library in C or if you like the the <cmath> library in C++.

The C++11 standard has: ceil, floor, round, trunk, nearbyint and rint. The first two are from previous standards and work in Visual C++. The remaining functions were added with C++11. They don’t work in VC++, at least not with the math library. I’m not certain when the next version of Visual C++ will be released and even if these new standards will be implemented with it.

The ceil and floor functions are not rounding functions from an accounting point of view. They return the nearest integer to the argument passed. The ceil function rounds up while the floor function rounds down. Not what I want in a round function.

The question is: how do I round a floating point number in C or C++?

In business there’s a few common rounding conventions: round to the nearest 2 decimals, nearest dollar or nearest thousand or millions of dollars.

Take this number: 123,456,456.789.

Round to nearest 2 decimals: 123,456,456.79
To the nearest dollar:              123,456,457
To the nearest thousands:       132,456,000 (sometimes shown as 123,456)

The ROUND(num, decimals) function in Excel can handle these situations with ease. The decimal parameter can be negative, zero or positive.

ROUND(123,456,456.789, 2) = 123,456,456.79
ROUND(123,456,456.789, 0) = 123,456,457.00
ROUND(123,456,456.789, -3) = 123,456,000.00

In Visual Basic 6, the round function worked in a similar fashion except it didn’t allow for a negative decimal argument. If you wanted to round numbers, to say, the nearest thousand, you’d have to write code to do that.

What about C and C++? How do you round numbers?

There is no round function currently implemented in the <cmath> library. At least, not in VC++. The C Standard for <math.h> includes a round function but then why it’s it included in C++? It should. I can’t find an answer to that question.

The fact the C++11 standard added a round function means it was missing. It also means, if you want to round numbers based on the above conventions, you have to write some code to do it or pull in a user-created library with such a function.

In VC++ it’s possible to tap into the Math class in .NET and use its Round method except that sounds like bloat.

To Do. Write a C & C++ function that rounds a floating point number in the same manner as Excel. That’s for another day.