O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.1. Using Fractions

Problem

You need to work with fractions supplied by the user, such as 3 4/5 and 134/21. Your application needs to parse, multiply, and reduce fractions.

Solution

Use Jakarta Commons Lang’s Fraction class to parse and manipulate fractions. The following code demonstrates the parsing of a String containing a fraction:

import org.apache.commons.lang.math.Fraction;

String userInput = "23 31/37";
Fraction fraction = Fraction.getFraction( userInput );
double value = fraction.doubleValue( );

The String “23 31/37” is converted to a double value of 23.837837. A Fraction object is created by calling the Fraction.getFraction( ) method, and double value of the Fraction object is obtained with fraction.doubleValue( ).

Discussion

The Fraction class provides a number of operations that can be used to simplify the following expression to an improper fraction. The following code evaluates the expression in Figure 8-1 using Fraction:

import org.apache.commons.lang.math.Fraction;

Fraction numer1 = Fraction.getFraction( 3, 4 );
Fraction numer2 = Fraction.getFraction( 51, 3509 );

Fraction numerator = numer1.multiplyBy( numer2 );
Fraction denominator = Fraction.getFraction( 41, 59 );

Fraction fraction = numerator.divideBy( denominator );
Fraction result = fraction.reduce( );

System.out.println( "as Fraction: " + result.reduce( ).toString( ) );
System.out.println( "as double: " + result.doubleValue( ) );

Figure 8-1. Expression to be evaluated with Fraction

The previous example creates ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required