Duplicate of: round() for float in C++
I’m using VS2008 and I’ve included math.h but I still can’t find a round function. Does it exist?
I’m seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You may use C++11’s
std::round().If you are still stuck with older standards, you may use
std::floor(), which always rounds to the lower number, andstd::ceil(), which always rounds to the higher number.To get the normal rounding behaviour, you would indeed use
floor(i + 0.5).This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:
Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:
Only use the second approach if you are not low on resources and/or need to have control over the precision.