Rounding to nearest half?

******EXTREMELY NEW TO C++*****


C++ Question:
How do I round to the nearest half integer?
Example;
0 to 0.2 = 0
0.3 to 0.5 = 0.5
0.6-0.9 = 1

What's the formula for C++?

I found a way to do it in math but I want to know what I'd have to put in C++. It's (x*2+.5)remove decimal numbers and divide by 2. What do I put in place of "remove decimal"?

For ex; x = 8.4 using (x*2+.5)remove decimal then divide by 2.
8.4 * 2 = 16.8
16.8 + .5 = 17.3
17.3 - decimal = 17
17/2 = 8.5

I want to do something like;
cout << " Half number: << (x*2+.5)remove decimal/2 << endl;

What would I have to put in place of "remove decimal"?


Thank you!
******EXTREMELY NEW TO C++*****
<cmath> has the floor function that might help. (floor rounds down, ceil rounds up)

Math functions are detailed here...
http://www.cplusplus.com/reference/cmath/
Following wildblue:
std::cout << (floor((x*2)+0.5)/2);
THANK YOU! That's exactly what I needed.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cmath>

int main() 
{
    double a[] = { 0.23, 0.37, 0.63, 0.87, 1.12, 1.34, 1.62, 1.78 } ;
    
    // http://en.cppreference.com/w/cpp/numeric/math/round
    for( double d : a ) std::cout << std::showpoint << std::llround(d*2) / 2.0 << ' ' ; 
}

http://coliru.stacked-crooked.com/a/2589e8bd1257d502
Topic archived. No new replies allowed.