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.kuali.student.git.importer.ReportBlobSizePerBranch.java

private static BigDecimal getGB(BigDecimal counter) {

    return counter.divide(new BigDecimal(FileUtils.ONE_GB));

}

From source file:org.kuali.student.git.importer.ReportBlobSizePerBranch.java

private static BigDecimal getMB(BigDecimal counter) {

    return counter.divide(new BigDecimal(FileUtils.ONE_MB));

}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.BigDecimalSplitter.java

/**
 * Divide numerator by denominator. If impossible in exact mode, use
 * rounding./*from  w  ww  .  j av  a 2s .  co  m*/
 */
protected static 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:Main.java

public static BigDecimal calculateDiscountAmt(BigDecimal Discount, BigDecimal DiscountAmt) {
    if (DiscountAmt == null || Discount.compareTo(BigDecimal.ZERO) == 0)
        return BigDecimal.ZERO;
    else {/*  w w  w. j av  a 2  s . c  o  m*/
        BigDecimal discountPerc = Discount.divide(new BigDecimal(100));
        return DiscountAmt.multiply(discountPerc);
    }
}

From source file:org.springframework.data.simpledb.attributeutil.AmazonSimpleDBUtil.java

public static BigDecimal decodeRealNumberRange(String value, int maxDigitsRight, BigDecimal offsetValue) {
    BigDecimal offsetNumber = new BigDecimal(value);
    BigDecimal shiftMultiplier = new BigDecimal(Math.pow(BASE, maxDigitsRight));
    BigDecimal tempVal0 = offsetValue.multiply(shiftMultiplier);
    BigDecimal tempVal = (offsetNumber.subtract(tempVal0));
    return (tempVal.divide(shiftMultiplier));
}

From source file:com.konakart.util.TaxUtils.java

/**
 * Calculates the tax for one or more items
 * //from ww  w  . j a  v a 2s. c  o m
 * @param taxRate
 *            tax rate as a percentage
 * @param cost
 *            cost of a single item
 * @param quantity
 *            Number of items
 * @param scale
 *            This is the scale used for the precision of the calculations. It is contained in
 *            the ADMIN_CURRENCY_DECIMAL_PLACES configuration variable.
 * @param rule
 *            The rule to be used which should be either TAX_PER_ITEM or TAX_ON_TOTAL.
 *            <ul>
 *            <li>
 *            TaxUtils.TAX_PER_ITEM : The tax is calculated for a single item, to the number of
 *            decimal places defined by scale. Then this value is multiplied by the quantity.
 *            <li>
 *            TaxUtils.TAX_ON_TOTAL : The tax is calculated for the total amount (single item
 *            cost x quantity).
 *            </ul>
 * @return Returns the tax amount
 * 
 */
public static BigDecimal getTaxAmount(BigDecimal taxRate, BigDecimal cost, int quantity, int scale, int rule) {
    if (taxRate == null || cost == null || quantity == 0) {
        return new BigDecimal(0);
    }

    BigDecimal lTaxRate = taxRate.divide(new BigDecimal(100));

    if (rule == TAX_PER_ITEM) {
        BigDecimal taxPerItem = cost.multiply(lTaxRate);
        taxPerItem = taxPerItem.setScale(scale, BigDecimal.ROUND_HALF_UP);
        BigDecimal totalTax = taxPerItem.multiply(new BigDecimal(quantity));
        totalTax = totalTax.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return totalTax;
    } else if (rule == TAX_ON_TOTAL) {
        BigDecimal totalPrice = cost.multiply(new BigDecimal(quantity));
        BigDecimal totalTax = totalPrice.multiply(lTaxRate);
        totalTax = totalTax.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return totalTax;
    }

    // Should never get this far
    return new BigDecimal(0);
}

From source file:com.spaceprogram.simplejpa.util.AmazonSimpleDBUtil.java

public static BigDecimal decodeRealNumberRange(String value, int maxDigitsRight, BigDecimal offsetValue) {
    BigDecimal offsetNumber = new BigDecimal(value);
    BigDecimal shiftMultiplier = new BigDecimal(Math.pow(10, maxDigitsRight));
    BigDecimal tempVal0 = offsetValue.multiply(shiftMultiplier);
    //        System.out.println("tempVal0=" + tempVal0);
    BigDecimal tempVal = (offsetNumber.subtract(tempVal0));
    //        System.out.println("tempVal=" + tempVal);
    return (tempVal.divide(shiftMultiplier));
}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * /*from  w  w w .j  ava2s.com*/
 * @param args
 * @return
 * @throws ScriptException
 */
private static Object parse(String[] args, Hstore hstore, Object object, ResultOptions options)
        throws ScriptException {

    if (object == null) {
        throw new ScriptException(ScriptException.ERROR_RESULT_IS_NULL + " PARSE");
    }

    HstoreParser<?> parser = hstore.getParser(object.getClass());

    if (args.length < 1) {
        throw new ScriptException(ScriptException.ERROR_INVALID_ARGUMENT_COUNT + " PARSE: " + args.length);
    }
    if (parser == null) {
        throw new ScriptException(ScriptException.ERROR_PARSER_IS_NULL + " PARSE");
    }

    try {
        Pattern p = PATTERN_ARRAY;
        Matcher m = p.matcher(args[0]);

        if (m.find()) {
            String param = m.group(1);
            int index = Integer.valueOf(m.group(2));
            Object array = parser.getValue(param, object);

            Object indexedObject = null;
            if (array != null) {
                if (List.class.isAssignableFrom(array.getClass())) {
                    indexedObject = ((List<?>) array).get(index);
                } else if (Collection.class.isAssignableFrom(array.getClass())) {
                    Iterator<?> iterator = ((Collection<?>) array).iterator();
                    int counter = 0;
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if ((counter++) == index) {
                            indexedObject = o;
                            break;
                        }
                    }
                }

                if (args.length > 1) {
                    String[] nextArgs = new String[args.length - 1];
                    nextArgs = Arrays.copyOfRange(args, 1, args.length);
                    return parse(nextArgs, hstore, indexedObject, options);
                } else {
                    return indexedObject;
                }
            }
        } else {
            Object value = parser.getValue(args[0], object);
            if (args.length > 1) {
                try {
                    long divisor = Long.parseLong(args[1]);
                    int precision = 2;
                    boolean groupingUsed = false;
                    if (args.length > 2) {
                        precision = Integer.parseInt(args[2]);
                    }
                    if (args.length > 3) {
                        groupingUsed = ("t".equals(args[3].toLowerCase())
                                || "true".equals(args[3].toLowerCase()));
                    }
                    NumberFormat format = (options != null ? DecimalFormat.getInstance(options.getLocale())
                            : DecimalFormat.getInstance());
                    format.setMaximumFractionDigits(precision);
                    format.setGroupingUsed(groupingUsed);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    //System.out.println("Converting number: " + args[0] + "=" + String.valueOf(value));
                    BigDecimal number = new BigDecimal(String.valueOf(value));
                    return format.format(number.divide(new BigDecimal(divisor)));
                } catch (Exception e) {
                    //can not return parsed element
                }
            }
            //System.out.println("PARAM object: " + args[0] + " -> " + value + " of " + object.toString());
            return value;
        }
    } catch (HstoreParseException e) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + e.getMessage());
    } catch (Throwable t) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + t.getMessage());
    }

    return null;
}

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

public static BigDecimal average(Object... objects) {
    long count = count(objects);
    BigDecimal divisor = count == 0 ? null : BigDecimal.valueOf(count);
    BigDecimal dividend = divisor == null ? null : sum(objects);
    BigDecimal result = dividend == null ? null : dividend.divide(divisor);
    return result;
}

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

public static BigInteger getRawUnitsFromDisplayString(CSAsset asset, String display) {
    BigDecimal result = null;//from w ww.  j  av  a2s .c  o m
    try {
        //System.out.println("Start to get raw units from: " + display);
        result = new BigDecimal(display);
    } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
        return null;
    }

    // Reverse apply the multiple
    int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset);
    if (decimalPlaces != 0) {
        result = result.movePointRight(decimalPlaces);
    }
    // FIXME: what if multiple is 0.0? ignore? error?
    //   double multiple = asset.getMultiple();
    //   BigDecimal m = new BigDecimal(String.valueOf(multiple));
    //   result = result.divide(m, MathContext.DECIMAL32);

    //System.out.println("multiplier=" + m + ", removed multiplier =" + display);

    double interestRate = asset.getInterestRate();

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

    Date issueDate = asset.getIssueDate();
    DateTime d1 = new DateTime(issueDate);
    DateTime d2 = new DateTime();
    int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds());

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

    BigDecimal elapsedSeconds = new BigDecimal(seconds);
    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.divide(new BigDecimal(String.valueOf(interestMultipler)), MathContext.DECIMAL32);

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

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

    //System.out.println("result floored = " + result.toPlainString());

    String resultString = result.toPlainString();
    return new BigInteger(resultString);
}