Skip to content

Commit

Permalink
CLDR-15954 Small cleanup to Rational, make it extend Number
Browse files Browse the repository at this point in the history
  • Loading branch information
macchiati committed Mar 16, 2024
1 parent 6d1c2e5 commit d81d7bb
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions tools/cldr-code/src/main/java/org/unicode/cldr/util/Rational.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
*
* @author markdavis
*/
public final class Rational implements Comparable<Rational> {
public final class Rational extends Number implements Comparable<Rational> {
private static final long serialVersionUID = 1L;
private static final Pattern INT_POWER_10 = Pattern.compile("10*");
public final BigInteger numerator;
public final BigInteger denominator;
Expand Down Expand Up @@ -298,17 +299,24 @@ public BigDecimal toBigDecimal(MathContext mathContext) {
}
}

@Override
public double doubleValue() {
if (denominator.equals(BigInteger.ZERO) && numerator.equals(BigInteger.ZERO)) {
return Double.NaN;
}
return new BigDecimal(numerator)
.divide(new BigDecimal(denominator), MathContext.DECIMAL64)
.doubleValue();
return toBigDecimal(MathContext.DECIMAL64).doubleValue();
}

@Override
public float floatValue() {
if (denominator.equals(BigInteger.ZERO) && numerator.equals(BigInteger.ZERO)) {
return Float.NaN;
}
return toBigDecimal(MathContext.DECIMAL32).floatValue();
}

public BigDecimal toBigDecimal() {
return toBigDecimal(MathContext.UNLIMITED);
return toBigDecimal(MathContext.DECIMAL128); // prevent failures due to repeating fractions
}

public static Rational of(BigDecimal bigDecimal) {
Expand Down Expand Up @@ -736,4 +744,14 @@ public boolean approximatelyEquals(Rational b) {
public boolean approximatelyEquals(Number b) {
return approximatelyEquals(Rational.of(b.doubleValue()), EPSILON);
}

@Override
public int intValue() {
return toBigDecimal().intValue();
}

@Override
public long longValue() {
return toBigDecimal().longValue();
}
}

0 comments on commit d81d7bb

Please sign in to comment.