How numbers are rounded

How are floats rounded to integers in C++? Does it only round up, or does it work like this:

1
2
3
1.1 = 1
1.4 = 1
1.9 = 2
I'm pretty sure truncation is compiler independent but will almost always be down (floor).
Yea, your right, just tested it, it rounds down.
AFAIK it just removes the non-integer part.

1
2
3
4
1.1 = 1
2.6 = 2
-1.2 = -1
//etc 
If you need integer numbers that are correctly rounded, just add 0.5 before converting to integer.
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
double round(double num) 
{
    return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5);
}
int round2int(double num)
{
    return (int) round( num);
}

int main()
{
    cout << "  x    (int)x   (int)x +0.5   round(x)  round2int(x)" << endl;
    cout << "====   ======   ===========   ========  ============" << endl;
    for(int i(0); i < 21; ++i)
    {
        double x = 1.0 - (0.1 * i);
        cout.width(6);
        cout << x;
        cout.width(7);
        cout << (int)x;
        cout.width(14);
        cout << (int) (x + 0.5);
        cout.width(11);
        cout << round(x);
        cout.width(14);
        cout << round2int(x) << endl;
    }
}

  x    (int)x   (int)x +0.5   round(x)  round2int(x)
====   ======   ===========   ========  ============
     1      1             1          1             1
   0.9      0             1          1             1
   0.8      0             1          1             1
   0.7      0             1          1             1
   0.6      0             1          1             1
   0.5      0             1          1             1
   0.4      0             0          0             0
   0.3      0             0          0             0
   0.2      0             0          0             0
   0.1      0             0          0             0
     0      0             0         -0             0
  -0.1      0             0         -0             0
  -0.2      0             0         -0             0
  -0.3      0             0         -0             0
  -0.4      0             0         -0             0
  -0.5      0             0         -1            -1
  -0.6      0             0         -1            -1
  -0.7      0             0         -1            -1
  -0.8      0             0         -1            -1
  -0.9      0             0         -1            -1
    -1     -1             0         -1            -1
Press any key to continue . . .


Edit:
The round() function should probably be the following to stop it rounding 0.0 to -0.0
1
2
3
4
double round(double num) 
{
    return (num < 0.0) ? ceil(num - 0.5) : floor(num + 0.5);
}

Last edited on
Topic archived. No new replies allowed.