Alex Herbert created NUMBERS-217:
------------------------------------
Summary: BigFraction to round using a MathContext
Key: NUMBERS-217
URL: https://issues.apache.org/jira/browse/NUMBERS-217
Project: Commons Numbers
Issue Type: New Feature
Components: fraction
Reporter: Alex Herbert
Allow rounding of a BigFraction to BigDecimal using a MathContext.
Current rounding uses a scale passed to BigDecimal divide. This allows the
number of digits after the decimal point to be specified. However this requires
knowledge of the current decimal representation of the number to obtain a
BigDecimal floating-point representation with a desired number of digits of
precision.
The MathContext allows the digits of precision to be set, rather than the
number of digits after the decimal place:
{code:java}
// 1e-20 is a representable double
BigFraction f = BigFraction.of(
BigInteger.ONE,
new BigInteger("100000000000000000000")
);
// 16 digits after the decimal place is not enough
System.out.println(f.bigDecimalValue(16, RoundingMode.HALF_EVEN));
// 16 digits of precision is OK
System.out.println(f.bigDecimalValue(MathContext.DECIMAL64));
// This is not a representable double
BigFraction f1 = BigFraction.of(
BigInteger.ONE,
new BigInteger("100000000000000000001")
);
System.out.println(f1.bigDecimalValue(MathContext.DECIMAL64));
// More precision
System.out.println(f1.bigDecimalValue(MathContext.DECIMAL128));
// Not a representable double
System.out.println(f1.bigDecimalValue(MathContext.DECIMAL128).doubleValue());{code}
Prints:
{noformat}
0E-10
1E-20
1.000000000000000E-20
9.999999999999999999900000000000000E-21
1.0E-20{noformat}
--
This message was sent by Atlassian Jira
(v8.20.10#820010)