Search code examples
apachemathroundingfractions

Round outcome Fraction Apache Math Common


Is it possible to round the fraction, e.g., 3/2 becomes 1+1/2 and 11/2 becomes 5+1/2 that is produced using Apache Common Math?

Attempt

Fraction f = new Fraction(3, 2);

System.out.println(f.abs());

FractionFormat format = new FractionFormat();

String s = format.format(f);

System.out.println(s);

results in:

3 / 2
3 / 2

Solution

  • It looks like what you are looking for is a Mixed Number.

    Since I don't think Apache Fractions has this built in, you can use the following custom formatter:

    public static String formatAsMixedNumber(Fraction frac) {
        int sign = Integer.signum(frac.getNumerator())
                * Integer.signum(frac.getDenominator());
        frac = frac.abs();
        int wholePart = frac.intValue();
        Fraction fracPart = frac.subtract(new Fraction(wholePart));
        return (sign == -1 ? "-" : "")
                + wholePart
                + (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
    }