Search⌘ K

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:

  1. If the decimal part is less than .5: Round down, i.e., drop the decimal part.

  2. If the decimal part is greater than or equal to .5: Round up, i.e., drop the decimal part and add 11 if the number if positive, and subtract 11 if negative.

Some examples are given below.

  • Rounding 3.143.14 gives 33: 0.140.14 is less than 0.50.5, so 0.140.14 is dropped

  • Rounding 1.25-1.25 gives 1-1 ...