Java Code Examples for java.math.BigDecimal#remainder()

The following examples show how to use java.math.BigDecimal#remainder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * remainder(BigDecimal, MathContext)
 */
public void testRemainderMathContextHALF_DOWN() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = -45;
    String b = "134432345432345748766876876723342238476237823787879183470";
    int bScale = 10;
    int precision = 75;
    RoundingMode rm = RoundingMode.HALF_DOWN;
    MathContext mc = new MathContext(precision, rm);
    String res = "1149310942946292909508821656680979993738625937.2065885780";
    int resScale = 10;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.remainder(bNumber, mc);
    assertEquals("incorrect quotient value", res, result.toString());
    assertEquals("incorrect quotient scale", resScale, result.scale());
}
 
Example 2
Source File: UniformFuturesOrderPlacingStrategy.java    From java-market-maker with Apache License 2.0 6 votes vote down vote up
/**
 * @param price        price to be rounded, has to be positive
 * @param roundingMode rounding mode that should be used (only {@link RoundingMode#UP} and {@link RoundingMode#DOWN}
 *                     are supported)
 * @return price rounded to tick size
 *
 * @throws IllegalArgumentException if {@code roundingMode} is neither {@link RoundingMode#UP} nor
 *                                  {@link RoundingMode#DOWN} or {@code price} is not positive
 */
static BigDecimal roundPriceToTickSize(final BigDecimal price, final RoundingMode roundingMode, final BigDecimal tickSize) {
    checkArgument(
        roundingMode == RoundingMode.UP || roundingMode == RoundingMode.DOWN,
        "Only rounding UP or DOWN supported"
    );
    checkArgument(price.compareTo(BigDecimal.ZERO) >= 0, "price=%s < 0", price);

    final BigDecimal remainder = price.remainder(tickSize);
    if (remainder.compareTo(BigDecimal.ZERO) == 0) {
        return price;
    }

    final BigDecimal result = price.subtract(remainder);
    if (roundingMode == RoundingMode.UP) {
        return result.add(tickSize);
    } else {
        return result;
    }
}
 
Example 3
Source File: ModuloEvaluator.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Object doWork(Object first, Object second) throws IOException{
  if(null == first){
    throw new IOException(String.format(Locale.ROOT,"Unable to %s(...) with a null numerator", constructingFactory.getFunctionName(getClass())));
  }
  
  if(null == second){
    throw new IOException(String.format(Locale.ROOT,"Unable to %s(...) with a null denominator", constructingFactory.getFunctionName(getClass())));
  }
  
  BigDecimal numerator = (BigDecimal)first;
  BigDecimal denominator = (BigDecimal)second;
  
  if(0 == denominator.compareTo(BigDecimal.ZERO)){
    throw new IOException(String.format(Locale.ROOT,"Unable to %s(...) with a 0 denominator", constructingFactory.getFunctionName(getClass())));
  }
  
  return numerator.remainder(denominator, MathContext.DECIMAL64);
}
 
Example 4
Source File: ValueDataUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the remainder (modulus) of A / B.
 *
 * @param metaA
 * @param dataA
 *          The dividend
 * @param metaB
 * @param dataB
 *          The divisor
 * @return The remainder
 * @throws KettleValueException
 */
public static Object remainder( ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB ) throws KettleValueException {
  if ( dataA == null || dataB == null ) {
    return null;
  }

  switch ( metaA.getType() ) {
    case ValueMetaInterface.TYPE_NUMBER:
      return new Double( metaA.getNumber( dataA ).doubleValue() % metaB.getNumber( dataB ).doubleValue() );
    case ValueMetaInterface.TYPE_INTEGER:
      return new Long( metaA.getInteger( dataA ) % metaB.getInteger( dataB ) );
    case ValueMetaInterface.TYPE_BIGNUMBER:
      BigDecimal aValue = metaA.getBigNumber( dataA );
      BigDecimal bValue = metaA.getBigNumber( dataB );
      BigDecimal result = aValue.remainder( bValue, MathContext.UNLIMITED );
      return removeTrailingZeroFractionOrScale( result );
    default:
      throw new KettleValueException( "The 'remainder' function only works on numeric data" );
  }
}
 
Example 5
Source File: FenixDigestUtils.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String getPrettyCheckSum(String digest) {
    int digestLength = digest.length();
    if ((digestLength % 2) == 1) {
        digest = "0" + digest;
        digestLength++;
    }

    byte[] result = new byte[digestLength / 2];

    for (int i = 0, min = 0, max = 2; max <= digestLength; min += 2, max += 2, i++) {
        result[i] = (byte) Integer.parseInt(digest.substring(min, max), 16);
    }

    BigDecimal bigDecimal = new BigDecimal("17");
    BigDecimal bigDecimal2 = new BigDecimal("101");

    for (int i = result.length; i > 0; i--) {
        short a = (short) (0xFF & result[i - 1]);
        bigDecimal = bigDecimal.multiply(bigDecimal2).add(BigDecimal.valueOf(a + i));
    }

    BigDecimal result2 = bigDecimal.remainder(new BigDecimal("99997"));
    return result2.abs().toPlainString();
}
 
Example 6
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * remainder(BigDecimal)
 */
public void testRemainder1() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = 45;
    String b = "134432345432345748766876876723342238476237823787879183470";
    int bScale = 10;
    String res = "3736186567876.876578956958765675671119238118911893939591735";
    int resScale = 45;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.remainder(bNumber);
    assertEquals("incorrect quotient value", res, result.toString());
    assertEquals("incorrect quotient scale", resScale, result.scale());
}
 
Example 7
Source File: BigDecimalCalculations.java    From oopsla15-artifact with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compute the sine of x to a given scale
 * @param x 
 *      the value of x
 * @param 
 *      scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal sin(BigDecimal x, int scale)
{
    if (x.signum() == 0)
    	return BigDecimal.ZERO;
    if (x.abs().compareTo(sincosNormalizePoint) >= 0 ) {
     x = x.remainder(twoPI, new MathContext(scale + 1));
    }
    if (x.signum() == -1)
        return sinTaylor(x.negate(), scale).negate();
    else 
    	return sinTaylor(x, scale);
}
 
Example 8
Source File: ConvertTypes.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void compute(final C input, final UnsignedLongType output) {
	final BigDecimal bd = BigDecimal.valueOf(input.getRealDouble());
	final BigDecimal r = bd.remainder(BigDecimal.ONE);
	if (r.compareTo(BigDecimal.ZERO) == 0) {
		output.set(bd.toBigIntegerExact().longValue());
	}
	else {
		output.set(bd.toBigInteger().longValue());
	}
}
 
Example 9
Source File: ConvertTypes.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void compute(final C input, final Unsigned128BitType output) {
	final BigDecimal bd = BigDecimal.valueOf(input.getRealDouble());
	final BigDecimal r = bd.remainder(BigDecimal.ONE);
	if (r.compareTo(BigDecimal.ZERO) == 0) {
		output.set(bd.toBigIntegerExact());
	}
	else {
		output.set(bd.toBigInteger());
	}
}
 
Example 10
Source File: Operators.java    From beanshell with Apache License 2.0 5 votes vote down vote up
static Object bigDecimalBinaryOperation(BigDecimal lhs, BigDecimal rhs, int kind)
    throws UtilEvalError
{
    switch(kind)
    {
        // arithmetic
        case PLUS:
            return lhs.add(rhs);

        case MINUS:
            return lhs.subtract(rhs);

        case STAR:
            return lhs.multiply(rhs);

        case SLASH:
            return lhs.divide(rhs);

        case MOD:
        case MODX:
            return lhs.remainder(rhs);

        case POWER:
        case POWERX:
            return lhs.pow(rhs.intValue());

        // can't shift floats
        case LSHIFT:
        case LSHIFTX:
        case RSIGNEDSHIFT:
        case RSIGNEDSHIFTX:
        case RUNSIGNEDSHIFT:
        case RUNSIGNEDSHIFTX:
            throw new UtilEvalError("Can't shift floatingpoint values");

    }
    throw new InterpreterError(
            "Unimplemented binary float operator");
}
 
Example 11
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the sine (sinus) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="http://en.wikipedia.org/wiki/Sine">Wikipedia: Sine</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the sine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated sine {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal sin(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());

	if (x.abs().compareTo(ROUGHLY_TWO_PI) > 0) {
		MathContext mc2 = new MathContext(mc.getPrecision() + 4, mathContext.getRoundingMode());
		BigDecimal twoPi = TWO.multiply(pi(mc2));
		x = x.remainder(twoPi, mc2);
	}

	BigDecimal result = SinCalculator.INSTANCE.calculate(x, mc);
	return round(result, mathContext);
}
 
Example 12
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the cosine (cosinus) of {@link BigDecimal} x.
 * 
 * <p>See: <a href="http://en.wikipedia.org/wiki/Cosine">Wikipedia: Cosine</a></p>
 * 
 * @param x the {@link BigDecimal} to calculate the cosine for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated cosine {@link BigDecimal} with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 */
public static BigDecimal cos(BigDecimal x, MathContext mathContext) {
	checkMathContext(mathContext);
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());

	if (x.abs().compareTo(ROUGHLY_TWO_PI) > 0) {
		MathContext mc2 = new MathContext(mc.getPrecision() + 4, mathContext.getRoundingMode());
		BigDecimal twoPi = TWO.multiply(pi(mc2), mc2);
		x = x.remainder(twoPi, mc2);
	}
	
	BigDecimal result = CosCalculator.INSTANCE.calculate(x, mc);
	return round(result, mathContext);
}
 
Example 13
Source File: DecimalHelper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static void getSparseFromBigDecimal(BigDecimal input, ByteBuf data, int startIndex,
                                           int scale, int nDecimalDigits) {

  // Initialize the buffer
  for (int i = 0; i < nDecimalDigits; i++) {
    data.setInt(startIndex + (i * INTEGER_SIZE), 0);
  }

  boolean sign = false;

  if (input.signum() == -1) {
    // negative input
    sign = true;
    input = input.abs();
  }

  // Truncate the input as per the scale provided
  input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);

  // Separate out the integer part
  BigDecimal integerPart = input.setScale(0, BigDecimal.ROUND_DOWN);

  int destIndex = nDecimalDigits - roundUp(scale) - 1;

  while (integerPart.compareTo(BigDecimal.ZERO) > 0) {
    // store the modulo as the integer value
    data.setInt(startIndex + (destIndex * INTEGER_SIZE), (integerPart.remainder(BASE_BIGDECIMAL)).intValue());
    destIndex--;
    // Divide by base 1 billion
    integerPart = (integerPart.divide(BASE_BIGDECIMAL)).setScale(0, BigDecimal.ROUND_DOWN);
  }

  /* Sparse representation contains padding of additional zeroes
   * so each digit contains MAX_DIGITS for ease of arithmetic
   */
  int actualDigits = scale % MAX_DIGITS;
  if (actualDigits != 0) {
    // Pad additional zeroes
    scale = scale + (MAX_DIGITS - actualDigits);
    input = input.setScale(scale, BigDecimal.ROUND_DOWN);
  }

  //separate out the fractional part
  BigDecimal fractionalPart = input.remainder(BigDecimal.ONE).movePointRight(scale);

  destIndex = nDecimalDigits - 1;

  while (scale > 0) {
    // Get next set of MAX_DIGITS (9) store it in the DrillBuf
    fractionalPart = fractionalPart.movePointLeft(MAX_DIGITS);
    BigDecimal temp = fractionalPart.remainder(BigDecimal.ONE);

    data.setInt(startIndex + (destIndex * INTEGER_SIZE), (temp.unscaledValue().intValue()));
    destIndex--;

    fractionalPart = fractionalPart.setScale(0, BigDecimal.ROUND_DOWN);
    scale -= MAX_DIGITS;
  }

  // Set the negative sign
  if (sign) {
    data.setInt(startIndex, data.getInt(startIndex) | 0x80000000);
  }
}
 
Example 14
Source File: OpModulus.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	Object leftOperand = getLeftOperand().getValueInternal(state).getValue();
	Object rightOperand = getRightOperand().getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.remainder(rightBigDecimal));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			this.exitTypeDescriptor = "D";
			return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			this.exitTypeDescriptor = "F";
			return new TypedValue(leftNumber.floatValue() % rightNumber.floatValue());
		}
		else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.remainder(rightBigInteger));
		}
		else if (leftNumber instanceof Long || rightNumber instanceof Long) {
			this.exitTypeDescriptor = "J";
			return new TypedValue(leftNumber.longValue() % rightNumber.longValue());
		}
		else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
			this.exitTypeDescriptor = "I";
			return new TypedValue(leftNumber.intValue() % rightNumber.intValue());
		}
		else {
			// Unknown Number subtypes -> best guess is double division
			return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
		}
	}

	return state.operate(Operation.MODULUS, leftOperand, rightOperand);
}
 
Example 15
Source File: Remainder.java    From vscrawler with Apache License 2.0 4 votes vote down vote up
@Override
public Object operate(SyntaxNode left, SyntaxNode right, StringContext stringContext) {

    Object leftValue = left.calculate(stringContext);
    Object rightValue = right.calculate(stringContext);
    if (leftValue == null || rightValue == null) {
        throw new EvaluateException("operate is null,left: " + leftValue + "  right:" + rightValue);
    }
    // 左右都不为空,开始计算
    // step one think as number
    if (leftValue instanceof Number && rightValue instanceof Number) {
        // 都是整数,则执行整数除法
        if (leftValue instanceof Integer && rightValue instanceof Integer) {
            return (Integer) leftValue % (Integer) rightValue;
        }

        // 包含小数,转double执行除法
        if (leftValue instanceof Double || rightValue instanceof Double || leftValue instanceof Float
                || rightValue instanceof Float) {
            return ((Number) leftValue).doubleValue() % ((Number) rightValue).doubleValue();
        }

        // 包含BigDecimal 转bigDecimal
        if (leftValue instanceof BigDecimal || rightValue instanceof BigDecimal) {
            if (leftValue instanceof BigDecimal && rightValue instanceof BigDecimal) {
                return ((BigDecimal) leftValue).remainder((BigDecimal) rightValue);
            }

            BigDecimal newLeft = XpathUtil.toBigDecimal((Number) leftValue);
            BigDecimal newRight = XpathUtil.toBigDecimal((Number) rightValue);
            return newLeft.remainder(newRight);
        }

        // 包含长整数,且不包含小数,全部转化为长整数计算
        if (leftValue instanceof Long || rightValue instanceof Long) {
            return ((Number) leftValue).longValue() % ((Number) rightValue).longValue();
        }

        // 兜底,用double执行计算
        return ((Number) leftValue).doubleValue() % ((Number) rightValue).doubleValue();
    }

    throw new EvaluateException(
            "remainder operate must with number parameter left:" + leftValue + " right:" + rightValue);

}
 
Example 16
Source File: BigDecimalXPathMathSupport.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected YangExpr doEvaluate(final YangBinaryOperator operator, final BigDecimalNumberExpr left,
        final BigDecimalNumberExpr right) {
    final BigDecimal l = left.getNumber();
    final BigDecimal r = right.getNumber();

    final BigDecimal result;
    switch (operator) {
        case DIV:
            result = l.divide(r);
            break;
        case EQUALS:
            return YangBooleanConstantExpr.of(l.equals(r));
        case GT:
            return YangBooleanConstantExpr.of(l.compareTo(r) > 0);
        case GTE:
            return YangBooleanConstantExpr.of(l.compareTo(r) >= 0);
        case LT:
            return YangBooleanConstantExpr.of(l.compareTo(r) < 0);
        case LTE:
            return YangBooleanConstantExpr.of(l.compareTo(r) <= 0);
        case MINUS:
            result = l.subtract(r);
            break;
        case MOD:
            result = l.remainder(r);
            break;
        case MUL:
            result = l.multiply(r);
            break;
        case NOT_EQUALS:
            return YangBooleanConstantExpr.of(!l.equals(r));
        case PLUS:
            result = l.add(r);
            break;
        default:
            throw new IllegalStateException("Unhandled operator " + operator);
    }

    return BigDecimalNumberExpr.of(result);
}
 
Example 17
Source File: BigDecimalType.java    From tddl with Apache License 2.0 4 votes vote down vote up
@Override
public Object mod(Object v1, Object v2) {
    BigDecimal i1 = convertFrom(v1);
    BigDecimal i2 = convertFrom(v2);
    return i1.remainder(i2);
}
 
Example 18
Source File: OpModulus.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	Object leftOperand = getLeftOperand().getValueInternal(state).getValue();
	Object rightOperand = getRightOperand().getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.remainder(rightBigDecimal));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			this.exitTypeDescriptor = "D";
			return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			this.exitTypeDescriptor = "F";
			return new TypedValue(leftNumber.floatValue() % rightNumber.floatValue());
		}
		else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.remainder(rightBigInteger));
		}
		else if (leftNumber instanceof Long || rightNumber instanceof Long) {
			this.exitTypeDescriptor = "J";
			return new TypedValue(leftNumber.longValue() % rightNumber.longValue());
		}
		else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) {
			this.exitTypeDescriptor = "I";
			return new TypedValue(leftNumber.intValue() % rightNumber.intValue());
		}
		else {
			// Unknown Number subtypes -> best guess is double division
			return new TypedValue(leftNumber.doubleValue() % rightNumber.doubleValue());
		}
	}

	return state.operate(Operation.MODULUS, leftOperand, rightOperand);
}
 
Example 19
Source File: DecimalUtility.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Function converts the BigDecimal and stores it in out internal sparse representation
 */
public static void getSparseFromBigDecimal(BigDecimal input, ByteBuf data, int startIndex, int scale, int nDecimalDigits) {

  // Initialize the buffer
  data.setZero(startIndex, nDecimalDigits * INTEGER_SIZE);

  boolean sign = false;

  if (input.signum() == -1) {
    // negative input
    sign = true;
    input = input.abs();
  }

  // Truncate the input as per the scale provided
  input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);

  // Separate out the integer part
  BigDecimal integerPart = input.setScale(0, BigDecimal.ROUND_DOWN);

  int destIndex = nDecimalDigits - roundUp(scale) - 1;

  // we use base 1 billion integer digits for out internal representation
  BigDecimal base = new BigDecimal(DIGITS_BASE);

  while (integerPart.compareTo(BigDecimal.ZERO) == 1) {
    // store the modulo as the integer value
    data.setInt(startIndex + destIndex * INTEGER_SIZE, integerPart.remainder(base).intValue());
    destIndex--;
    // Divide by base 1 billion
    integerPart = integerPart.divide(base, BigDecimal.ROUND_DOWN).setScale(0, BigDecimal.ROUND_DOWN);
  }

  /* Sparse representation contains padding of additional zeroes
   * so each digit contains MAX_DIGITS for ease of arithmetic
   */
  int actualDigits = scale % MAX_DIGITS;
  if (actualDigits != 0) {
    // Pad additional zeroes
    scale = scale + MAX_DIGITS - actualDigits;
    input = input.setScale(scale, BigDecimal.ROUND_DOWN);
  }

  //separate out the fractional part
  BigDecimal fractionalPart = input.remainder(BigDecimal.ONE).movePointRight(scale);

  destIndex = nDecimalDigits - 1;

  while (scale > 0) {
    // Get next set of MAX_DIGITS (9) store it in the DrillBuf
    fractionalPart = fractionalPart.movePointLeft(MAX_DIGITS);
    BigDecimal temp = fractionalPart.remainder(BigDecimal.ONE);

    data.setInt(startIndex + destIndex * INTEGER_SIZE, temp.unscaledValue().intValue());
    destIndex--;

    fractionalPart = fractionalPart.setScale(0, BigDecimal.ROUND_DOWN);
    scale -= MAX_DIGITS;
  }

  // Set the negative sign
  if (sign) {
    data.setInt(startIndex, data.getInt(startIndex) | 0x80000000);
  }
}
 
Example 20
Source File: DefaultBigDecimalMath.java    From big-math with MIT License 2 votes vote down vote up
/**
 * Returns the {@link BigDecimal} that is <code>x % y</code> using the current {@link MathContext}.
 *
 * @param x the x value
 * @param y the y value to divide
 * @return the resulting {@link BigDecimal} with the precision specified in the current {@link MathContext}
 * @see #currentMathContext()
 * @see BigDecimal#remainder(BigDecimal, MathContext)
 */
public static BigDecimal remainder(BigDecimal x, BigDecimal y) {
    return x.remainder(y, currentMathContext());
}