The fraction packages provides a fraction number type as well as fraction number formatting.
org.apache.commons.math.fraction.Fraction provides a fraction number type that forms the basis for the fraction functionality found in commons-math.
To create a fraction number, simply call the constructor passing in two integer arguments, the first being the numerator of the fraction and the second being the denominator:
Of special note with fraction construction, when a fraction is created it is always reduced to lowest terms.
The Fraction
class provides many unary and binary
fraction operations. These operations provide the means to add,
subtract, multiple and, divide fractions along with other functions similar to the real number functions found in
java.math.BigDecimal
:
Like fraction construction, for each of the fraction functions, the resulting fraction is reduced to lowest terms.
Fraction
instances can be converted to and from strings
using the
org.apache.commons.math.fraction.FractionFormat class.
FractionFormat
is a java.text.Format
extension and, as such, is used like other formatting objects (e.g.
java.text.SimpleDateFormat
):
To customize the formatting output, one or two
java.text.NumberFormat
instances can be used to construct
a FractionFormat
. These number formats control the
formatting of the numerator and denominator of the fraction:
Formatting's inverse operation, parsing, can also be performed by
FractionFormat
. To parse a fraction from a string,
simply call the parse
method: