Example usage for java.math BigDecimal abs

List of usage examples for java.math BigDecimal abs

Introduction

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

Prototype

public BigDecimal abs() 

Source Link

Document

Returns a BigDecimal whose value is the absolute value of this BigDecimal , and whose scale is this.scale() .

Usage

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

/**
 * @param dd//w  w w .java 2  s . co  m
 * @param decimalLen
 * @param degFmt
 * @return
 */
public static String convertToSignedDDMMMM(final BigDecimal dd, final int decimalLen,
        final DEGREES_FORMAT degFmt) {
    String sign = "";
    if (dd.compareTo(dd.abs()) < 0) {
        sign = "-";
    }

    String convertedAbs = convertToDDMMMM(dd, degFmt, DIRECTION.None, decimalLen);
    return sign + convertedAbs;
}

From source file:edu.ku.brc.util.LatLonConverter.java

/**
 * @param dd//w  ww  . j a v  a 2s .c om
 * @param decimalLen
 * @param detFmt
 * @return
 */
public static String convertToSignedDDDDDD(final BigDecimal dd, final int decimalLen,
        final DEGREES_FORMAT degFmt) {
    String sign = "";
    if (dd.compareTo(dd.abs()) < 0) {
        sign = "-";
    }

    String convertedAbs = convertToDDDDDD(dd, degFmt, DIRECTION.None, decimalLen);
    return sign + convertedAbs;
}

From source file:org.openbravo.advpaymentmngt.utility.APRM_MatchingUtility.java

/**
 * Split the given bank statement line only when it does not match with the amount of the given
 * transaction. It will create a clone of the given bank statement line with the difference
 * amount. The original bank statement line amounts will be set equal to the amounts in the
 * transaction// w w w.j a  va2  s.c o m
 * 
 */
private static void splitBankStatementLine(final FIN_Reconciliation reconciliation,
        final FIN_BankStatementLine bankStatementLine, final FIN_FinaccTransaction transaction) {
    try {
        OBContext.setAdminMode(true);
        if (reconciliation == null || bankStatementLine == null || transaction == null) {
            throw new OBException("splitBankStatementLine method requires not null parameters");
        }

        final BigDecimal bslAmount = bankStatementLine.getCramount().subtract(bankStatementLine.getDramount());
        final BigDecimal trxAmount = transaction.getDepositAmount().subtract(transaction.getPaymentAmount());

        // If amounts don't match we continue with the split
        if (bslAmount.compareTo(trxAmount) != 0) {
            if ("Y".equals(reconciliation.getPosted())) {
                // reconciliation posted not possible to split a row
                throw new OBException(OBMessageUtils.messageBD("APRM_SplitBSLReconciliationPosted"));
            }
            if (bankStatementLine.getFinancialAccountTransaction() != null
                    && bankStatementLine.getFinancialAccountTransaction().getReconciliation() != null) {
                throw new OBException(OBMessageUtils.messageBD("APRM_SplitBSLAlreadyMatched"));
            }

            // prevent trigger
            FIN_BankStatement bs = bankStatementLine.getBankStatement();
            bs.setProcessed(false);
            OBDal.getInstance().save(bs);
            OBDal.getInstance().flush();

            // Duplicate bank statement line with pending amount
            FIN_BankStatementLine clonedBSLine = (FIN_BankStatementLine) DalUtil.copy(bankStatementLine, true);
            final BigDecimal credit = bankStatementLine.getCramount().subtract(transaction.getDepositAmount());
            final BigDecimal debit = bankStatementLine.getDramount().subtract(transaction.getPaymentAmount());
            clonedBSLine.setCramount(credit);
            clonedBSLine.setDramount(debit);

            if (credit.compareTo(BigDecimal.ZERO) != 0 && debit.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal total = credit.subtract(debit);
                if (total.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setCramount(BigDecimal.ZERO);
                    clonedBSLine.setDramount(total.abs());
                } else {
                    clonedBSLine.setCramount(total);
                    clonedBSLine.setDramount(BigDecimal.ZERO);
                }
            } else {
                if (credit.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setCramount(BigDecimal.ZERO);
                    clonedBSLine.setDramount(credit.abs());
                }
                if (debit.compareTo(BigDecimal.ZERO) == -1) {
                    clonedBSLine.setDramount(BigDecimal.ZERO);
                    clonedBSLine.setCramount(debit.abs());
                }

            }

            // Set bankstatement line amounts with the matched transaction amounts
            bankStatementLine.setCramount(transaction.getDepositAmount());
            bankStatementLine.setDramount(transaction.getPaymentAmount());

            bs.setProcessed(true);

            // Save
            OBDal.getInstance().save(bs);
            OBDal.getInstance().save(clonedBSLine);
            OBDal.getInstance().save(bankStatementLine);
        }

    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.cirdles.calamari.algorithms.TukeyBiweight.java

public static ValueModel calculateTukeyBiweightMean(String name, double tuningConstant, double[] values) {
    // guarantee termination
    BigDecimal epsilon = BigDecimal.ONE.movePointLeft(10);
    int iterationMax = 100;
    int iterationCounter = 0;

    int n = values.length;
    // initial mean is median
    BigDecimal mean = new BigDecimal(calculateMedian(values));

    // initial sigma is median absolute deviation from mean = median (MAD)
    double deviations[] = new double[n];
    for (int i = 0; i < values.length; i++) {
        deviations[i] = StrictMath.abs(values[i] - mean.doubleValue());
    }//  ww  w. j  av  a 2 s.  c  o m
    BigDecimal sigma = new BigDecimal(calculateMedian(deviations)).max(BigDecimal.valueOf(SQUID_TINY_VALUE));

    BigDecimal previousMean;
    BigDecimal previousSigma;

    do {
        iterationCounter++;
        previousMean = mean;
        previousSigma = sigma;

        // init to zeroes
        BigDecimal[] deltas = new BigDecimal[n];
        BigDecimal[] u = new BigDecimal[n];
        BigDecimal sa = BigDecimal.ZERO;
        BigDecimal sb = BigDecimal.ZERO;
        BigDecimal sc = BigDecimal.ZERO;

        BigDecimal tee = new BigDecimal(tuningConstant).multiply(sigma);

        for (int i = 0; i < n; i++) {
            deltas[i] = new BigDecimal(values[i]).subtract(mean);
            if (tee.compareTo(deltas[i].abs()) > 0) {
                deltas[i] = new BigDecimal(values[i]).subtract(mean);
                u[i] = deltas[i].divide(tee, MathContext.DECIMAL128);
                BigDecimal uSquared = u[i].multiply(u[i]);
                sa = sa.add(deltas[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)).pow(2));
                sb = sb.add(BigDecimal.ONE.subtract(uSquared)
                        .multiply(BigDecimal.ONE.subtract(new BigDecimal(5.0).multiply(uSquared))));
                sc = sc.add(u[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)));
            }
        }

        sigma = bigDecimalSqrtBabylonian(sa.multiply(new BigDecimal(n))).divide(sb.abs(),
                MathContext.DECIMAL128);
        sigma = sigma.max(BigDecimal.valueOf(SQUID_TINY_VALUE));
        mean = previousMean.add(tee.multiply(sc).divide(sb, MathContext.DECIMAL128));

    } // both tests against epsilon must pass OR iterations top out
      // april 2016 Simon B discovered we need 101 iterations possible, hence the "<=" below
    while (((sigma.subtract(previousSigma).abs().divide(sigma, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            || mean.subtract(previousMean).abs().divide(mean, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            && (iterationCounter <= iterationMax));

    return new ValueModel(name, mean, "ABS", sigma);
}

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

private Double absolute() {
    Object object0 = inputs[0].getValue();

    try {/* w w  w. j  a  v  a2  s.c  o m*/
        BigDecimal d0 = new BigDecimal(object0.toString());

        return d0.abs().doubleValue();
    } catch (NumberFormatException exp) {
        log.error(null, exp);
    }

    return null;
}

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

/**
 * Converts BigDecimal to Degrees, Minutes and Decimal Seconds.
 * @param bd the DigDecimal to be converted.
 * @return a 3 piece string//from w w w.  j a  v a  2 s. c  o  m
 */
public static String convertToDDMMSS(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {

    if (bd.doubleValue() == 0.0) {
        return "0." + zeroes.substring(0, decimalLen);
    }

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

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = new BigDecimal(remainder.multiply(sixty).abs().intValue());
        BigDecimal secondsFraction = remainder.abs().multiply(sixty).subtract(minutes);
        BigDecimal seconds = secondsFraction.multiply(sixty);

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

        return decFormatter2.format(num) + " " + decFormatter2.format(minutes) + " "
                + decFormatter.format(seconds);

    }
    //else

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

    double minutes = remainder * 60.0;
    int minutesWhole = (int) Math.floor(minutes);
    double secondsFraction = minutes - minutesWhole;
    double seconds = secondsFraction * 60.0;

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    if (minutesWhole == 60) {
        whole += 1;
        minutesWhole = 0;
    }

    // round to 2 decimal places precision
    seconds = Math.round(seconds * 1000) / 1000.0;

    int secondsWhole = (int) Math.floor(seconds);
    if (secondsWhole == 60) {
        minutesWhole += 1;
        seconds = 0.0;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append(DEGREES_SYMBOL);
    }
    sb.append(' ');
    sb.append(minutesWhole);
    if (addMinSecsSyms)
        sb.append("'");
    sb.append(' ');

    sb.append(String.format("%2." + decimalLen + "f", seconds));
    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]);
        }
    }
    //System.err.println("["+sb.toString()+"]");
    //return whole + (DEGREES_FORMAT.None ? "\u00B0" : "") + " " + minutesWhole + " " + StringUtils.strip(String.format("%12.10f", new Object[] {seconds}), "0");
    return sb.toString();
}

From source file:org.onebusaway.admin.util.VehicleStatusBuilder.java

private String getLastUpdate(String timeReported) {
    String lastUpdate;// ww w  .ja v  a2 s  . c  o m
    BigDecimal difference = getTimeDifference(timeReported);
    if (difference.abs().compareTo(new BigDecimal(86400)) > 0) {
        //Calculate the difference in days
        BigDecimal days = difference.divide(new BigDecimal(86400), BigDecimal.ROUND_HALF_UP);
        lastUpdate = days.toPlainString() + " days";
    } else {
        if (difference.abs().compareTo(new BigDecimal(3600)) > 0) {
            //Calculate the difference in hours
            BigDecimal hours = difference.divide(new BigDecimal(3600), BigDecimal.ROUND_HALF_UP);
            lastUpdate = hours.toPlainString() + " hours";
        } else {
            if (difference.abs().compareTo(new BigDecimal(60)) > 0) {
                //Calculate the difference in minutes
                BigDecimal minutes = difference.divide(new BigDecimal(60), BigDecimal.ROUND_UP);
                lastUpdate = minutes.toPlainString() + " mins";
            } else {
                lastUpdate = difference + " sec";
            }
        }
    }
    return lastUpdate;
}

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

/**
 * Converts BigDecimal to Decimal Degrees.
 * @param bd the DigDecimal to be converted.
 * @param degreesFMT indicates whether to include the degrees symbol
 * @return a 1 piece string//  ww  w.j  a v a 2s  .  co  m
 */
public static String convertToDDDDDD(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {
    if (bd == null || bd.doubleValue() == 0.0) {
        return "0.0";
    }

    StringBuilder sb = new StringBuilder();

    sb.append(String.format("%" + decimalLen + "." + decimalLen + "f", bd.abs()));

    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append("\u00B0");

    }
    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 format(bd.abs()) + (degreesFMT == DEGREES_FORMAT.Symbol ? "\u00B0" : "");
    return sb.toString();
}

From source file:nl.strohalm.cyclos.utils.conversion.NumberConverter.java

public String toString(final T number) {
    if (number == null) {
        return null;
    }//from ww  w. ja v a2s .com
    BigDecimal bigDecimal = CoercionHelper.coerce(BigDecimal.class, number);

    // Convert to negative if on negativeToAbsoluteValue mode and number is not zero
    if (negativeToAbsoluteValue) {
        bigDecimal = bigDecimal.abs();
    }

    // For very small negative numbers, like 0.000001, avoid formatting as -0,00
    final BigDecimal delta = getDelta();
    if (bigDecimal.compareTo(BigDecimal.ZERO) < 0 && bigDecimal.compareTo(delta) > 0) {
        bigDecimal = BigDecimal.ZERO;
    }

    return numberFormat.format(bigDecimal);
}

From source file:com.rockagen.gnext.service.spring.AccountServImpl.java

/**
 * Balance enough?//  w ww .  jav a  2 s  .c  o  m
 *
 * @param account Account
 * @param amount  amount
 * @return true if enough
 */
private boolean checkBalance(Account account, BigDecimal amount) {
    BigDecimal tmp = account.getAvailableBalance().subtract(amount.abs());
    if ((tmp.compareTo(BigDecimal.ZERO)) < 0) {
        return false;
    }
    return true;

}