Creating the decimalValue method
For our Fraction class, it would be nice to have a method for converting a Fraction to a single primitive value. This is an easy computation which will result in a floating point or double number.
The decimal value of the fraction can be obtained by dividing a Fraction's numerator by its denominator.
Java considers a division operation as double or integer division based on the following rules:
-
If both the operands are integers then integer division is performed.
Integer division gives the quotient(integer) of the division and the remainder of the division is ignored/lost.
For example 12/5 is 2
-
If one of the operands is float or double then the division performed is double division and the result is a double value.
For example 12.0/5 is 2.4
Double division needs to be performed to get a decimal value. The following example casts both values to doubles, but it would be sufficient to only cast one value to a double as division between an int and a double in Java results in a double.
/**
* Returns the decimal value of the Fraction
* Precondition: None
* Postcondition: None
* @param None
* @return A double representing the decimal value of this Fraction
*/
public double decimalValue()
{
//Explicitly change the data type of numerator and denominator. Eg. (double)var;
//return the decimal value by dividing the numerator and denominator, both converted to double
}
Testing
- Un-comment the code in main that prints the decimal value of the two fractions.