## 9 Fractions## 9.1 OverviewThe fraction packages provides a fraction number type as well as fraction number formatting. ## 9.2 Fraction NumbersFraction and BigFraction provide fraction number type that forms the basis for the fraction functionality found in Commons-Math. The former one can be used for fractions whose numerators and denominators are small enough to fit in an int (taking care of intermediate values) while the second class should be used when there is a risk the numerator and denominator grow very large. A fraction number, can be built from two integer arguments representing numerator and denominator or from a double which will be approximated: Fraction f = new Fraction(1, 3); // 1 / 3 Fraction g = new Fraction(0.25); // 1 / 4 Of special note with fraction construction, when a fraction is created it is always reduced to lowest terms.
The Fraction lhs = new Fraction(1, 3); Fraction rhs = new Fraction(2, 5); Fraction answer = lhs.add(rhs); // add two fractions answer = lhs.subtract(rhs); // subtract two fractions answer = lhs.abs(); // absolute value answer = lhs.reciprocal(); // reciprocal of lhs Like fraction construction, for each of the fraction functions, the resulting fraction is reduced to lowest terms. ## 9.3 Fraction Formatting and Parsing
FractionFormat format = new FractionFormat(); // default format Fraction f = new Fraction(2, 4); String s = format.format(f); // s contains "1 / 2", note the reduced fraction
To customize the formatting output, one or two
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE); // create fraction format with custom number format // when one number format is used, both numerator and // denominator are formatted the same FractionFormat format = new FractionFormat(nf); Fraction f = new Fraction(2000, 3333); String s = format.format(c); // s contains "2.000 / 3.333" NumberFormat nf2 = NumberFormat.getInstance(Locale.US); // create fraction format with custom number formats format = new FractionFormat(nf, nf2); s = format.format(f); // s contains "2.000 / 3,333"
Formatting's inverse operation, parsing, can also be performed by
FractionFormat ff = new FractionFormat(); Fraction f = ff.parse("-10 / 21"); |