Rounding Double Type Variables

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: 0.250.25 is less than 0.50.5, so 0.250.25 is dropped.

  • Rounding 2.712.71 gives 33: 0.710.71 is greater than 0.50.5, and the number is positive. Thus, drop 0.710.71 and add 11 to it.

  • Rounding −2.5-2.5 gives −3-3: 0.50.5 is equal to 0.50.5, and the number is negative. Thus, drop 0.50.5 and subtract 1 from it.

Converting into a Java program

Well, how do we convert this into a Java program? Let’s make our lives a little easier and only consider positive numbers.

The operations we have under our belt so far are arithmetic operations and typecasting. Try to think about what we can do with them!

What does typecasting give us?

If we cast any double type variable using (int), the decimal is dropped. Well, this at least works for 50% of numbers, i.e., all the numbers with a decimal part less than 0.50.5. However, for all the numbers with decimal part greater than or equal to 0.50.5, we will have an incorrect answer, i.e., 1 unit less.

Get hands-on with 1200+ tech skills courses.