1 package tim.prune.drew.jpeg;
\r
4 * Immutable class for holding a rational number without loss of precision.
\r
5 * Based on Drew Noakes' Metadata extractor at http://drewnoakes.com
\r
7 public class Rational
\r
9 /** Holds the numerator */
\r
10 private final int _numerator;
\r
12 /** Holds the denominator */
\r
13 private final int _denominator;
\r
17 * @param inNumerator numerator of fraction (upper number)
\r
18 * @param inDenominator denominator of fraction (lower number)
\r
20 public Rational(int inNumerator, int inDenominator)
\r
22 // Could throw exception if denominator is zero
\r
23 _numerator = inNumerator;
\r
24 _denominator = inDenominator;
\r
29 * @return the value of the specified number as a <code>double</code>.
\r
30 * This may involve rounding.
\r
32 public double doubleValue()
\r
34 if (_denominator == 0) return 0.0;
\r
35 return (double)_numerator / (double)_denominator;
\r
39 * @return the value of the specified number as an <code>int</code>.
\r
40 * This may involve rounding or truncation.
\r
42 public final int intValue()
\r
44 if (_denominator == 0) return 0;
\r
45 return _numerator / _denominator;
\r
49 * @return the denominator.
\r
51 public final int getDenominator()
\r
53 return _denominator;
\r
57 * @return the numerator.
\r
59 public final int getNumerator()
\r
65 * Checks if this rational number is an Integer, either positive or negative.
\r
67 public boolean isInteger()
\r
69 // number is integer if the denominator is 1, or if the remainder is zero
\r
70 return (_denominator == 1
\r
71 || (_denominator != 0 && (_numerator % _denominator == 0)));
\r
76 * @return a string representation of the object of form <code>numerator/denominator</code>.
\r
78 public String toString()
\r
80 return "" + _numerator + "/" + _denominator;
\r
85 * Compares two <code>Rational</code> instances, returning true if they are equal
\r
86 * @param inOther the Rational to compare this instance to.
\r
87 * @return true if instances are equal, otherwise false.
\r
89 public boolean equals(Rational inOther)
\r
91 // Could also attempt to simplify fractions to lowest common denominator before compare
\r
92 return _numerator == inOther._numerator && _denominator == inOther._denominator;
\r