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 , so is dropped
-
Rounding gives : is less than , so is dropped.
-
Rounding gives : is greater than , and the number is positive. Thus, drop and add to it.
-
Rounding gives : is equal to , and the number is negative. Thus, drop 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 . However, for all the numbers with decimal part greater than or equal to , we will have an incorrect answer, i.e., 1 unit less.
Get hands-on with 1400+ tech skills courses.