Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:jp.co.acroquest.endosnipe.report.converter.util.calc.BigDecimalCalculator.java

public Object sub(Object obj1, Object obj2) {
    BigDecimal decimalData1 = (BigDecimal) obj1;
    BigDecimal decimalData2 = (BigDecimal) obj2;

    return (Object) (decimalData1.subtract(decimalData2));
}

From source file:org.gradle.performance.measure.DataSeries.java

public DataSeries(Iterable<? extends Amount<Q>> values) {
    for (Amount<Q> value : values) {
        if (value != null) {
            add(value);/*w  ww.  j  av a 2s .c  o m*/
        }
    }

    if (isEmpty()) {
        average = null;
        median = null;
        max = null;
        min = null;
        standardError = null;
        return;
    }

    Amount<Q> total = get(0);
    Amount<Q> min = get(0);
    Amount<Q> max = get(0);
    for (int i = 1; i < size(); i++) {
        Amount<Q> amount = get(i);
        total = total.plus(amount);
        min = min.compareTo(amount) <= 0 ? min : amount;
        max = max.compareTo(amount) >= 0 ? max : amount;
    }
    List<Amount<Q>> sorted = Lists.newArrayList(this);
    Collections.sort(sorted);
    Amount<Q> medianLeft = sorted.get((sorted.size() - 1) / 2);
    Amount<Q> medianRight = sorted.get((sorted.size() - 1) / 2 + 1 - sorted.size() % 2);
    median = medianLeft.plus(medianRight).div(2);
    average = total.div(size());
    this.min = min;
    this.max = max;

    BigDecimal sumSquares = BigDecimal.ZERO;
    Units<Q> baseUnits = average.getUnits().getBaseUnits();
    BigDecimal averageValue = average.toUnits(baseUnits).getValue();
    for (int i = 0; i < size(); i++) {
        Amount<Q> amount = get(i);
        BigDecimal diff = amount.toUnits(baseUnits).getValue();
        diff = diff.subtract(averageValue);
        diff = diff.multiply(diff);
        sumSquares = sumSquares.add(diff);
    }
    // This isn't quite right, as we may lose precision when converting to a double
    BigDecimal result = BigDecimal
            .valueOf(Math
                    .sqrt(sumSquares.divide(BigDecimal.valueOf(size()), RoundingMode.HALF_UP).doubleValue()))
            .setScale(2, RoundingMode.HALF_UP);

    standardError = Amount.valueOf(result, baseUnits);
}

From source file:org.openvpms.component.system.common.jxpath.BigDecimalOperationSubtract.java

@Override
public Object computeValue(EvalContext context) {
    BigDecimal l = TypeConversionUtil.bigDecimalValue(args[0].computeValue(context));
    BigDecimal r = TypeConversionUtil.bigDecimalValue(args[1].computeValue(context));
    return l.subtract(r);
}

From source file:ch.algotrader.service.algo.TrailingLimitOrderService.java

private BigDecimal calculateLimit(TrailingLimitOrder algoOrder, BigDecimal last) {

    if (algoOrder.getSide() == Side.BUY) {
        return last.subtract(algoOrder.getTrailingAmount());
    } else {//from  w  w  w. ja va  2 s.  c o m
        return last.add(algoOrder.getTrailingAmount());
    }
}

From source file:org.libreplan.business.planner.entities.SigmoidFunction.java

private BigDecimal decimalPart(BigDecimal bd) {
    return bd.subtract(intPart(bd));
}

From source file:com.github.jessemull.microflex.stat.statbigdecimal.GeometricMeanBigDecimalTest.java

/**
 * Corrects any rounding errors due to differences in the implementation of
 * the statistic between the Apache and MicroFlex libraries
 * @param    BigDecimal    the first result
 * @param    BigDecimal    the second result
 * @return                 corrected results
 *///from w  w w  . java2  s.co m
private static BigDecimal[] correctRoundingErrors(BigDecimal bd1, BigDecimal bd2) {

    BigDecimal[] array = new BigDecimal[2];
    int scale = mc.getPrecision();

    while (!bd1.equals(bd2) && scale > mc.getPrecision() / 4) {

        bd1 = bd1.setScale(scale, RoundingMode.HALF_DOWN);
        bd2 = bd2.setScale(scale, RoundingMode.HALF_DOWN);

        if (bd1.subtract(bd1.ulp()).equals(bd2)) {
            bd1 = bd1.subtract(bd1.ulp());
        }

        if (bd1.add(bd1.ulp()).equals(bd2)) {
            bd1 = bd1.add(bd1.ulp());
        }

        scale--;
    }

    array[0] = bd1;
    array[1] = bd2;

    return array;
}

From source file:org.jumpmind.symmetric.io.data.transform.AdditiveColumnTransform.java

public String transform(IDatabasePlatform platform, DataContext context, TransformColumn column,
        TransformedData data, Map<String, String> sourceValues, String newValue, String oldValue)
        throws IgnoreColumnException, IgnoreRowException {

    BigDecimal multiplier = new BigDecimal(1.00);

    if (StringUtils.isNotBlank(column.getTransformExpression())) {
        multiplier = new BigDecimal(column.getTransformExpression());
    }/*  ww w . j  a  v a2s  . c o  m*/

    Table table = platform.getTableFromCache(data.getCatalogName(), data.getSchemaName(), data.getTableName(),
            false);
    if (table == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find the target table {}", data.getFullyQualifiedTableName());
        }
        throw new IgnoreColumnException();
    } else if (table.getColumnWithName(column.getTargetColumnName()) == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find the target column {}", column.getTargetColumnName());
        }
        throw new IgnoreColumnException();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Old, new, transform expression as received: " + oldValue + ", " + newValue + ", "
                    + column.getTransformExpression());
        }

        if (!StringUtils.isNotBlank(newValue) || data.getSourceDmlType() == DataEventType.DELETE) {
            newValue = "0";
        }
        if (!StringUtils.isNotBlank(oldValue)) {
            oldValue = "0";
        }

        BigDecimal delta = new BigDecimal(newValue);
        delta = delta.subtract(new BigDecimal(oldValue));
        delta = delta.multiply(multiplier);
        newValue = delta.toString();

        String quote = platform.getDdlBuilder().isDelimitedIdentifierModeOn()
                ? platform.getDatabaseInfo().getDelimiterToken()
                : "";
        StringBuilder sql = new StringBuilder(String.format("update %s set %s=%s+(%s) where ",
                getFullyQualifiedTableName(platform, data.getSchemaName(), data.getCatalogName(),
                        data.getTableName()),
                quote + column.getTargetColumnName() + quote, quote + column.getTargetColumnName() + quote,
                newValue));

        String[] keyNames = data.getKeyNames();
        List<Column> columns = new ArrayList<Column>();
        List<String> keyValuesList = new ArrayList<String>();
        boolean addedFirstKey = false;
        for (int i = 0; i < keyNames.length; i++) {
            Column targetCol = table.getColumnWithName(keyNames[i]);
            if (targetCol != null) {
                columns.add(targetCol);
                keyValuesList.add(sourceValues.get(keyNames[i]));
                if (addedFirstKey) {
                    sql.append("and ");
                } else {
                    addedFirstKey = true;
                }
                sql.append(quote);
                sql.append(keyNames[i]);
                sql.append(quote);
                sql.append("=? ");
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("SQL: " + sql);
        }
        ISqlTransaction transaction = context.findTransaction();
        if (0 < transaction.prepareAndExecute(sql.toString(),
                platform.getObjectValues(context.getBatch().getBinaryEncoding(),
                        keyValuesList.toArray(new String[keyValuesList.size()]),
                        columns.toArray(new Column[columns.size()])))) {
            throw new IgnoreColumnException();
        }

    }

    return newValue;
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees and Decimal Minutes.
 * @param bd the DigDecimal to be converted.
 * @return a 2 piece string//ww  w . j ava2s  .c o  m
 */
public static String convertToDDMMMM(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {
    if (bd.doubleValue() == 0.0) {
        return "0.0";
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = remainder.multiply(sixty).abs();

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]");
        return decFormatter2.format(num) + " " + decFormatter2.format(minutes);

    }
    //else

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    //System.out.println("["+whole+"]["+String.format("%10.10f", new Object[] {minutes})+"]");

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append("\u00B0");
    }
    sb.append(' ');

    // round to four decimal places of precision
    //minutes = Math.round(minutes*10000) / 10000;

    sb.append(String.format("%" + 2 + "." + decimalLen + "f", minutes));
    if (addMinSecsSyms)
        sb.append("'");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //return whole + (degreesFMT == DEGREES_FORMAT.Symbol ? "\u00B0" : "") + " " + StringUtils.strip(String.format("%10.10f", new Object[] {minutes}), "0");
    return sb.toString();

}

From source file:ch.algotrader.service.algo.TrailingLimitOrderService.java

public void adjustLimit(TrailingLimitOrder algoOrder, BigDecimal last) throws ReflectiveOperationException {

    Optional<TrailingLimitOrderStateVO> optional = getAlgoOrderState(algoOrder);
    if (optional.isPresent()) {

        TrailingLimitOrderStateVO orderState = optional.get();

        synchronized (orderState) {

            LimitOrder limitOrder = orderState.getLimitOrder();
            BigDecimal increment = algoOrder.getIncrement();

            if (limitOrder != null) {

                BigDecimal limit = limitOrder.getLimit();
                BigDecimal newLimit = calculateLimit(algoOrder, last);
                if (algoOrder.getSide() == Side.BUY) {
                    if (newLimit.subtract(limit).compareTo(increment) >= 0) {
                        modifyOrder(algoOrder, orderState, newLimit);
                    }// w  ww.  j ava 2s . c om
                } else {
                    if (limit.subtract(newLimit).compareTo(increment) >= 0) {
                        modifyOrder(algoOrder, orderState, newLimit);
                    }
                }
            }
        }
    }
}

From source file:org.yccheok.jstock.analysis.ArithmeticOperator.java

private Double subtraction() {
    Object object0 = inputs[0].getValue();
    Object object1 = inputs[1].getValue();

    try {// w w  w  .  j a  v a2s  .  co  m
        BigDecimal d0 = new BigDecimal(object0.toString());
        BigDecimal d1 = new BigDecimal(object1.toString());

        BigDecimal result = d0.subtract(d1);
        return result.doubleValue();
    } catch (NumberFormatException exp) {
        log.error(null, exp);
    }

    return null;
}