public static BigRational valueOf(Boolean positive, string integerPart, string fractionPart, string fractionRepeatPart, string exponentPart) { BigRational result = ZERO; if (fractionRepeatPart != null && fractionRepeatPart.Length > 0) { BigInteger lotsOfNines = BigInteger.TEN.pow(fractionRepeatPart.Length).subtract(BigInteger.ONE); result = valueOf(new BigInteger(fractionRepeatPart), lotsOfNines); } if (fractionPart != null && fractionPart.Length > 0) { result = result.add(valueOf(new BigInteger(fractionPart))); result = result.divide(BigInteger.TEN.pow(fractionPart.Length)); } if (integerPart != null && integerPart.Length > 0) { result = result.add(new BigInteger(integerPart)); } if (exponentPart != null && exponentPart.Length > 0) { int exponent = int.Parse(exponentPart); BigInteger powerOfTen = BigInteger.TEN.pow(Math.Abs(exponent)); result = exponent >= 0 ? result.multiply(powerOfTen) : result.divide(powerOfTen); } if (!positive) { result = result.negate(); } return(result); }
/** * Creates a rational number of the specified integer and fraction parts. * * <p>Useful to create numbers like 3 1/2 (= three and a half = 3.5) by calling * <code>BigRational.valueOf(3, 1, 2)</code>.</p> * <p>To create a negative rational only the integer part argument is allowed to be negative: * to create -3 1/2 (= minus three and a half = -3.5) call <code>BigRational.valueOf(-3, 1, 2)</code>.</p> * * @param integer the integer part int value * @param fractionNumerator the fraction part numerator int value (negative not allowed) * @param fractionDenominator the fraction part denominator int value (0 or negative not allowed) * @return the rational number * @throws ArithmeticException if the fraction part denominator is 0 (division by zero), * or if the fraction part numerator or denominator is negative */ public static BigRational valueOf(int integer, int fractionNumerator, int fractionDenominator) { if (fractionNumerator < 0 || fractionDenominator < 0) { throw new ArithmeticException("Negative value"); } BigRational integerPart = valueOf(integer); BigRational fractionPart = valueOf(fractionNumerator, fractionDenominator); return(integerPart.isPositive() ? integerPart.add(fractionPart) : integerPart.subtract(fractionPart)); }