Rounding Double Type Variables
Let's look at a cool application of typecasting.
Simple rules of conversion
In the last lesson, we saw how typecasting a double
type variable to an int
type variable only results in the decimal part of the number being dropped. This is likely not how you learned to convert decimal numbers to integers. The conversion you have likely studied follows these rules:
-
If the decimal part is less than .5: Round down, i.e., drop the decimal part.
-
If the decimal part is greater than or equal to .5: Round up, i.e., drop the decimal part and add if the number if positive, and subtract if negative.
Some examples are given below.
-
Rounding gives : is less than ...