COSC120
Using Type Casting to "Round Off" a Value in Memory

The examples below show you how to "round off" a floating point number--in memory. For example, you may wish to store 6.38 as 6.0 instead or you may wish to store dollar & cents amounts to the nearest cent, as in $6.38 rather than $6.38412.

1.    To round a non-negative floating point value to the nearest "integer":

A.     floatValue = int (floatValue+ 0.5);
Ex: Let floatValue = 6.38
6.38 + 0.5 = 6.88
int(6.88) = 6
floatValue is now 6.0
B.    floatValue = floor(floatValue+0.5);
The floor function requires you to include math.h.
    floor(x) rounds x to the largest integer not greater than x.
    floor takes a double float argument.
    floor returns a double float result.

Ex:     Let floatValue = 6.38
          6.38 + 0.5 = 6.88
          floor(6.88) = 6.0
          floatValue is now 6.0

2.    To round to nearest tenth:
A.    floatValue = float(int(floatValue * 10 + 0.5)) / 10;
                    OR
B.     floatValue = floor(floatValue*10+0.5)/10;
Ex for method A:
Let floatValue = 8.673
floatValue*10 = 86.73
86.73 + 0.5 = 87.23
int(87.23) = 87
float (87) = 87.0
87.0 / 10 = 8.7
floatValue is now 8.7
Ex for method B:
Let floatValue = 8.673
floatValue*10+0.5 = 87.23
floor(87.23) = 87.0
87.0 / 10 = 8.7
floatValue is now 8.7
3.    To round to nearest hundredth:
The steps are the same as for rounding to the nearest tenth, but you multiply by 100 (instead of 10) and later divide by 100 (instead of 10).

When dealing with dollars and cents, it is desirable to round off to the nearest cent in memory.

                Ex:     moneyValue = floor(floatValue*100+0.5)/100;

                            If moneyValue was stored as 8.12345, it is now stored as 8.12.

Another handy math.h function is "ceil" (for "ceiling).

ceil(x) rounds up the smallest integer not less than x.
        x is a double float.
        ceil(x) returns a double float.
        ceill is the long double version. It takes a long double argument and returns a long double result.