Rounding Double Type Variables
Understand how to round double type variables to integers in Java by applying correct typecasting and arithmetic rules. Explore how adding or subtracting 0.5 before casting helps handle rounding for positive and negative numbers following standard rounding principles.
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 , so is dropped
-
Rounding gives ...