Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

In this page you can find the example usage for java.math BigDecimal divide.

Prototype

public BigDecimal divide(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

From source file:org.multibit.utils.CSMiscUtils.java

public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) {
    if (asset == null)
        return BigDecimal.ZERO;
    CoinSparkGenesis genesis = asset.getGenesis();
    if (genesis == null)
        return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated.
    int chargeBasisPoints = genesis.getChargeBasisPoints();
    int chargeExponent = genesis.getChargeFlatExponent();
    int chargeMantissa = genesis.getChargeFlatMantissa();
    int qtyExponent = genesis.getQtyExponent();
    int qtyMantissa = genesis.getQtyMantissa();

    double interestRate = asset.getInterestRate();
    Date issueDate = asset.getIssueDate();

    BigDecimal result = new BigDecimal(rawQuantity.toString());

    //System.out.println("interest rate = " + interestRate);
    //System.out.println("issue date = " + issueDate);

    //System.out.println("raw units =" + result);

    // 1. Compute interest
    if (issueDate != null && interestRate != 0.0) {

        BigDecimal rate = new BigDecimal(String.valueOf(interestRate));
        rate = rate.divide(new BigDecimal(100));
        rate = rate.add(BigDecimal.ONE);
        //interestRate = interestRate / 100;

        //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString());

        // get years elapsed
        DateTime d1 = new DateTime(issueDate);
        DateTime d2 = new DateTime();

        //System.out.println("Issue: " + d1 + "   Now: " + d2);
        int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds());

        //System.out.println("...Number of seconds difference: " + seconds);

        BigDecimal elapsedSeconds = new BigDecimal(seconds);

        //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString());

        // To avoid exception, we need to set a precision.
        // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
        // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable
        BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR),
                MathContext.DECIMAL32);
        //System.out.println("...Number of years difference: " + elapsedYears.toPlainString());

        double base = elapsedSeconds.doubleValue();
        double exp = elapsedYears.doubleValue();
        //System.out.println("...base=" + base + "  exponent=" + exp);
        double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue());

        //System.out.println("interest multipler =" + interestMultipler);

        result = result.multiply(new BigDecimal(interestMultipler));

        //System.out.println("raw units with interest multiplier =" + result);

        result = result.setScale(0, RoundingMode.DOWN);

        //System.out.println("raw units with interest multiplier, floored =" + result);

    }//from w  w w  . ja  v a2  s. c  om

    // 2. Apply multiple
    int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset);
    BigDecimal display = result;
    if (decimalPlaces != 0) {
        //       System.out.println(">>>>> display = " + display.toPlainString());
        display = result.movePointLeft(decimalPlaces);
        //       System.out.println(">>>>> display = " + display.toPlainString());
    }

    //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent);
    //   double multiple = asset.getMultiple();
    // let's just do it for now to make sure code is corret   
    //if (multiple != 1.0)
    //   BigDecimal m = new BigDecimal(String.valueOf(multiple));
    //   BigDecimal display = result.multiply(m);

    //System.out.println("multiplier=" + m + ", display=" + display);
    // Stripping zeros from internal zero with different scale does not work, so use 
    // JDK bug still seems to exist
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539
    // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes
    int cmpZeroResult = display.compareTo(BigDecimal.ZERO);
    if (decimalPlaces == 0) {
        display = display.stripTrailingZeros();
    }

    // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead.
    if (0 == cmpZeroResult) {
        display = BigDecimal.ZERO;
    }
    return display;
}

From source file:adalid.commons.util.ObjUtils.java

public static BigDecimal xDividedIntoY(Object x, Object y) {
    BigDecimal bx = NumUtils.numberToBigDecimal(x);
    BigDecimal by = bx == null ? null : NumUtils.numberToBigDecimal(y);
    return bx == null || by == null ? null : bx.divide(by);
}

From source file:com.moneychanger.core.helper.bitcoin.BitcoinClient.java

protected static double roundToTwoDecimals(double amount) {
    BigDecimal amountTimes100 = new BigDecimal(amount * 100.0D + 0.5D);
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0D));

    return roundedAmount.doubleValue();
}

From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java

private static void configurePolygonSymbolizer(final SurfacePolygonSymbolizer symbolizer,
        final BigDecimal minValue, final BigDecimal maxValue) throws FilterEvaluationException {
    final PolygonColorMap templateColorMap = symbolizer.getColorMap();
    final PolygonColorMap newColorMap = new PolygonColorMap_Impl();

    // retrieve stuff from template-entries
    final PolygonColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$
    final PolygonColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$

    // Fill//w  w w  .  j a  va  2s  .  co m
    final Color fromPolygonColor = fromEntry.getFill().getFill(null);
    final Color toPolygonColor = toEntry.getFill().getFill(null);
    final double polygonOpacity = fromEntry.getFill().getOpacity(null);

    // Stroke
    final Color fromLineColor = fromEntry.getStroke().getStroke(null);
    final Color toLineColor = toEntry.getStroke().getStroke(null);
    final double lineOpacity = fromEntry.getStroke().getOpacity(null);

    // step width
    final double stepWidth = fromEntry.getTo(null);

    // scale of the step width
    final BigDecimal setScale = new BigDecimal(fromEntry.getFrom(null)).setScale(0, BigDecimal.ROUND_FLOOR);
    final int stepWidthScale = setScale.intValue();

    // get rounded values below min and above max (rounded by first decimal)
    // as a first try we will generate isareas by using class steps of 0.1
    // later, the classes will be created by using user defined class steps.
    // for that we fill an array of calculated (later user defined values) from max to min
    final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR);
    final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING);

    final BigDecimal polygonStepWidth = new BigDecimal(stepWidth).setScale(stepWidthScale,
            BigDecimal.ROUND_FLOOR);
    int numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth)).intValue();
    // set to provide more them 1 or 0 classes. in such cases the color map will not be created, that results error.  
    if (numOfClasses < 2) {
        numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth.divide(new BigDecimal(4))))
                .intValue();
    }
    for (int currentClass = 0; currentClass < numOfClasses; currentClass++) {
        final double fromValue = minDecimal.doubleValue() + currentClass * polygonStepWidth.doubleValue();
        final double toValue = minDecimal.doubleValue() + (currentClass + 1) * polygonStepWidth.doubleValue();

        // Stroke
        Color lineColor;
        if (fromLineColor == toLineColor)
            lineColor = fromLineColor;
        else
            lineColor = interpolateColor(fromLineColor, toLineColor, currentClass, numOfClasses);

        // Fill
        final Color polygonColor = interpolateColor(fromPolygonColor, toPolygonColor, currentClass,
                numOfClasses);
        lineColor = polygonColor;

        final Stroke stroke = StyleFactory.createStroke(lineColor, lineOpacity, 1);

        final Fill fill = StyleFactory.createFill(polygonColor, polygonOpacity);

        final ParameterValueType label = StyleFactory.createParameterValueType("Isoflche " + currentClass); //$NON-NLS-1$
        final ParameterValueType from = StyleFactory.createParameterValueType(fromValue);
        final ParameterValueType to = StyleFactory.createParameterValueType(toValue);

        final PolygonColorMapEntry colorMapEntry = new PolygonColorMapEntry_Impl(fill, stroke, label, from, to);
        newColorMap.addColorMapClass(colorMapEntry);
    }

    symbolizer.setColorMap(newColorMap);
}

From source file:ru.paradoxs.bitcoin.client.BitcoinClient.java

/**
 * Rounds a double to the nearest two decimals, rounding UP.
 * Not proud of this code, but it works.
 *///from www  .  j a  va  2s . co  m
protected static BigDecimal roundToTwoDecimals(BigDecimal amount) {
    BigDecimal amountTimes100 = amount.multiply(new BigDecimal(100)).add(new BigDecimal("0.5"));
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0));

    return roundedAmount;
}

From source file:org.bitcoin.client.BitcoinClient.java

/**
 * Rounds a double to the nearest dwo decimals, rounding UP.
 * Not proud of this code, but it works.
 *//*w  w  w .j av a2  s  .c  o  m*/
protected static double roundToTwoDecimals(double amount) {
    BigDecimal amountTimes100 = new BigDecimal(amount * 100 + 0.5);
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0));

    return roundedAmount.doubleValue();
}

From source file:co.nubetech.apache.hadoop.BigDecimalSplitter.java

/**
 * Divide numerator by denominator. If impossible in exact mode, use
 * rounding.//from  w  ww .  j  av a 2  s.  c  o  m
 */
protected BigDecimal tryDivide(BigDecimal numerator, BigDecimal denominator) {
    try {
        return numerator.divide(denominator);
    } catch (ArithmeticException ae) {
        return numerator.divide(denominator, BigDecimal.ROUND_HALF_UP);
    }
}

From source file:org.egov.works.services.WorkProgressAbstractReportService.java

/**
 * Converting given amount to show in Crores with no of decimal points to be rounded off
 *
 * @param amount/*w ww .  j  a  va 2s .c om*/
 * @param decimalPoints
 * @return
 */
public BigDecimal getRoundedOfAmount(final Object amount, final int decimalPoints) {
    final int dividingFactor = 10000000; // 1 Crore
    if (amount != null) {
        final BigDecimal divisor = new BigDecimal(dividingFactor);
        final BigDecimal amountBD = (BigDecimal) amount;
        final BigDecimal result = amountBD.divide(divisor);
        return result.setScale(decimalPoints, RoundingMode.HALF_UP);
    } else
        return null;
}

From source file:com.stratio.cassandra.lucene.schema.mapping.BigDecimalMapper.java

/**
 * Builds a new {@link BigDecimalMapper} using the specified max number of digits for the integer and decimal
 * parts.//from   w  w  w . j  a v a2  s  .co  m
 *
 * @param field         The name of the field.
 * @param column        The name of the column to be mapped.
 * @param indexed       If the field supports searching.
 * @param sorted        If the field supports sorting.
 * @param integerDigits The max number of digits for the integer part. If {@code null}, the {@link
 *                      #DEFAULT_INTEGER_DIGITS} will be used.
 * @param decimalDigits The max number of digits for the decimal part. If {@code null}, the {@link
 *                      #DEFAULT_DECIMAL_DIGITS} will be used.
 */
public BigDecimalMapper(String field, String column, Boolean indexed, Boolean sorted, Integer integerDigits,
        Integer decimalDigits) {
    super(field, column, indexed, sorted, AsciiType.instance, UTF8Type.instance, Int32Type.instance,
            LongType.instance, IntegerType.instance, FloatType.instance, DoubleType.instance,
            DecimalType.instance);

    // Setup integer part mapping
    if (integerDigits != null && integerDigits <= 0) {
        throw new IndexException("Positive integer part digits required");
    }
    this.integerDigits = integerDigits == null ? DEFAULT_INTEGER_DIGITS : integerDigits;

    // Setup decimal part mapping
    if (decimalDigits != null && decimalDigits <= 0) {
        throw new IndexException("Positive decimal part digits required");
    }
    this.decimalDigits = decimalDigits == null ? DEFAULT_DECIMAL_DIGITS : decimalDigits;

    int totalDigits = this.integerDigits + this.decimalDigits;
    BigDecimal divisor = BigDecimal.valueOf(BASE).pow(this.decimalDigits);
    BigDecimal dividend = BigDecimal.valueOf(BASE).pow(totalDigits).subtract(BigDecimal.valueOf(1));
    complement = dividend.divide(divisor);
}

From source file:com.stratio.cassandra.index.schema.ColumnMapperBigDecimal.java

/**
 * Builds a new {@link ColumnMapperBigDecimal} using the specified max number of digits for the integer and decimal
 * parts./*from ww  w .j  av  a  2 s . co m*/
 *
 * @param integerDigits The max number of digits for the integer part. If {@code null}, the {@link
 *                      #DEFAULT_INTEGER_DIGITS} will be used.
 * @param decimalDigits The max number of digits for the decimal part. If {@code null}, the {@link
 *                      #DEFAULT_DECIMAL_DIGITS} will be used.
 */
@JsonCreator
public ColumnMapperBigDecimal(@JsonProperty("integer_digits") Integer integerDigits,
        @JsonProperty("decimal_digits") Integer decimalDigits) {
    super(new AbstractType<?>[] { AsciiType.instance, UTF8Type.instance, Int32Type.instance, LongType.instance,
            IntegerType.instance, FloatType.instance, DoubleType.instance, DecimalType.instance },
            new AbstractType[] {});

    // Setup integer part mapping
    if (integerDigits != null && integerDigits <= 0) {
        throw new IllegalArgumentException("Positive integer part digits required");
    }
    this.integerDigits = integerDigits == null ? DEFAULT_INTEGER_DIGITS : integerDigits;

    // Setup decimal part mapping
    if (decimalDigits != null && decimalDigits <= 0) {
        throw new IllegalArgumentException("Positive decimal part digits required");
    }
    this.decimalDigits = decimalDigits == null ? DEFAULT_DECIMAL_DIGITS : decimalDigits;

    int totalDigits = this.integerDigits + this.decimalDigits;
    BigDecimal divisor = BigDecimal.valueOf(10).pow(this.decimalDigits);
    BigDecimal dividend = BigDecimal.valueOf(10).pow(totalDigits).subtract(BigDecimal.valueOf(1));
    complement = dividend.divide(divisor);
}