Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:com.osafe.services.OsafePayPalServices.java

private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart) throws GenericEntityException {
    encoder.add("CURRENCYCODE", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        encoder.add("L_NUMBER" + line, item.getProductId());
        encoder.add("L_NAME" + line, item.getName());
        encoder.add("L_AMT" + line, item.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;//  w  w  w.  j av a 2s.c  om
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            encoder.add("L_NUMBER" + line, item.getProductId());
            encoder.add("L_NAME" + line, item.getName() + " Adjustments");
            encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            encoder.add("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        encoder.add("L_NUMBER" + line, "N/A");
        encoder.add("L_NAME" + line, "Order Adjustments");
        encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, "1");
        line++;
    }
    encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //encoder.add("SHIPPINGAMT", "0.00");
    //encoder.add("TAXAMT", "0.00");
    encoder.add("SHIPPINGAMT", cart.getTotalShipping().setScale(2).toPlainString());
    encoder.add("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
    encoder.add("AMT", cart.getGrandTotal().setScale(2).toPlainString());
    //encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //NOTE: The docs say this is optional but then won't work without it
    //encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
}

From source file:ips1ap101.lib.base.util.StrUtils.java

public static boolean esObjetoEnRango(Object objeto, Object minimo, Object maximo) {
    boolean es = true;
    //      EnumTipoDatoParametro tipo;
    if (objeto == null) {
        return false;
    } else if (objeto instanceof String) {
        //          tipo = EnumTipoDatoParametro.ALFANUMERICO;
        String val1 = (String) objeto;
        String min1 = (String) minimo;
        String max1 = (String) maximo;
        if (min1 != null && val1.compareTo(min1) < 0) {
            es = false;/* ww  w.j  a  v a2s  .  com*/
        }
        if (max1 != null && val1.compareTo(max1) > 0) {
            es = false;
        }
    } else if (objeto instanceof Integer) {
        //          tipo = EnumTipoDatoParametro.ENTERO;
        Integer val4 = (Integer) objeto;
        Integer min4 = (Integer) minimo;
        Integer max4 = (Integer) maximo;
        if (min4 != null && val4.compareTo(min4) < 0) {
            es = false;
        }
        if (max4 != null && val4.compareTo(max4) > 0) {
            es = false;
        }
    } else if (objeto instanceof Long || objeto instanceof BigInteger) {
        //          tipo = EnumTipoDatoParametro.ENTERO_GRANDE;
        Long val5 = objeto instanceof BigInteger ? ((BigInteger) objeto).longValue() : (Long) objeto;
        Long min5 = (Long) minimo;
        Long max5 = (Long) maximo;
        if (min5 != null && val5.compareTo(min5) < 0) {
            es = false;
        }
        if (max5 != null && val5.compareTo(max5) > 0) {
            es = false;
        }
    } else if (objeto instanceof BigDecimal) {
        //          tipo = EnumTipoDatoParametro.NUMERICO;
        BigDecimal val2 = (BigDecimal) objeto;
        BigDecimal min2 = (BigDecimal) minimo;
        BigDecimal max2 = (BigDecimal) maximo;
        if (min2 != null && val2.compareTo(min2) < 0) {
            es = false;
        }
        if (max2 != null && val2.compareTo(max2) > 0) {
            es = false;
        }
    } else if (objeto instanceof Timestamp) {
        //          tipo = EnumTipoDatoParametro.FECHA_HORA;
        Timestamp val3 = (Timestamp) objeto;
        Timestamp min3 = (Timestamp) minimo;
        Timestamp max3 = (Timestamp) maximo;
        if (min3 != null && val3.compareTo(min3) < 0) {
            es = false;
        }
        if (max3 != null && val3.compareTo(max3) > 0) {
            es = false;
        }
    } else {
        return false;
    }
    return es;
}

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

/**
 * Returns a list of BigDecimals one element longer than the list of input
 * splits. This represents the boundaries between input splits. All splits
 * are open on the top end, except the last one.
 * //from ww w.j a v a  2  s.  co  m
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:
 * 
 * [0, 5) [5, 8) [8, 12) [12, 18] note the closed interval for the last
 * split.
 */
List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) throws SQLException {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:com.intuit.karate.Script.java

public static AssertionResult matchNestedObject(char delimiter, String path, MatchType matchType,
        Object actRoot, Object actObject, Object expObject, ScriptContext context) {
    logger.trace("path: {}, actual: '{}', expected: '{}'", path, actObject, expObject);
    if (expObject == null) {
        if (actObject != null) {
            return matchFailed(path, actObject, expObject, "actual value is not null");
        }// w  w  w . j ava  2 s .co m
        return AssertionResult.PASS; // both are null
    }
    if (expObject instanceof String) {
        ScriptValue actValue = new ScriptValue(actObject);
        return matchStringOrPattern(delimiter, path, matchType, actRoot, actValue, expObject.toString(),
                context);
    } else if (expObject instanceof Map) {
        if (!(actObject instanceof Map)) {
            return matchFailed(path, actObject, expObject, "actual value is not of type 'map'");
        }
        Map<String, Object> expMap = (Map) expObject;
        Map<String, Object> actMap = (Map) actObject;
        if (matchType != MatchType.CONTAINS && actMap.size() > expMap.size()) { // > is because of the chance of #ignore
            return matchFailed(path, actObject, expObject,
                    "actual value has more keys than expected - " + actMap.size() + ":" + expMap.size());
        }
        for (Map.Entry<String, Object> expEntry : expMap.entrySet()) { // TDDO should we assert order, maybe XML needs this ?
            String key = expEntry.getKey();
            String childPath = path + delimiter + key;
            AssertionResult ar = matchNestedObject(delimiter, childPath, MatchType.EQUALS, actRoot,
                    actMap.get(key), expEntry.getValue(), context);
            if (!ar.pass) {
                return ar;
            }
        }
        return AssertionResult.PASS; // map compare done
    } else if (expObject instanceof List) {
        List expList = (List) expObject;
        List actList = (List) actObject;
        int actCount = actList.size();
        int expCount = expList.size();
        if (matchType != MatchType.CONTAINS && actCount != expCount) {
            return matchFailed(path, actObject, expObject,
                    "actual and expected arrays are not the same size - " + actCount + ":" + expCount);
        }
        if (matchType == MatchType.CONTAINS || matchType == MatchType.CONTAINS_ONLY) { // just checks for existence
            for (Object expListObject : expList) { // for each expected item in the list
                boolean found = false;
                for (int i = 0; i < actCount; i++) {
                    Object actListObject = actList.get(i);
                    String listPath = buildListPath(delimiter, path, i);
                    AssertionResult ar = matchNestedObject(delimiter, listPath, MatchType.EQUALS, actRoot,
                            actListObject, expListObject, context);
                    if (ar.pass) { // exact match, we found it
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return matchFailed(path + "[*]", actObject, expListObject,
                            "actual value does not contain expected");
                }
            }
            return AssertionResult.PASS; // all items were found
        } else { // exact compare of list elements and order
            for (int i = 0; i < expCount; i++) {
                Object expListObject = expList.get(i);
                Object actListObject = actList.get(i);
                String listPath = buildListPath(delimiter, path, i);
                AssertionResult ar = matchNestedObject(delimiter, listPath, MatchType.EQUALS, actRoot,
                        actListObject, expListObject, context);
                if (!ar.pass) {
                    return matchFailed(listPath, actListObject, expListObject, "[" + ar.message + "]");
                }
            }
            return AssertionResult.PASS; // lists (and order) are identical
        }
    } else if (ClassUtils.isPrimitiveOrWrapper(expObject.getClass())) {
        return matchPrimitive(path, actObject, expObject);
    } else if (expObject instanceof BigDecimal) {
        BigDecimal expNumber = (BigDecimal) expObject;
        if (actObject instanceof BigDecimal) {
            BigDecimal actNumber = (BigDecimal) actObject;
            if (actNumber.compareTo(expNumber) != 0) {
                return matchFailed(path, actObject, expObject, "not equal (big decimal)");
            }
        } else {
            BigDecimal actNumber = convertToBigDecimal(actObject);
            if (actNumber == null || actNumber.compareTo(expNumber) != 0) {
                return matchFailed(path, actObject, expObject, "not equal (primitive : big decimal)");
            }
        }
        return AssertionResult.PASS;
    } else { // this should never happen
        throw new RuntimeException("unexpected type: " + expObject.getClass());
    }
}

From source file:org.apache.sqoop.mapreduce.db.BigDecimalSplitter.java

/**
 * Returns a list of BigDecimals one element longer than the list of input
 * splits.  This represents the boundaries between input splits.  All splits
 * are open on the top end, except the last one.
 *
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:/*from   ww w.jav  a  2s . co m*/
 *
 * [0, 5)
 * [5, 8)
 * [8, 12)
 * [12, 18] note the closed interval for the last split.
 */
protected List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal)
        throws SQLException {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:com.mirth.connect.donkey.model.channel.MetaDataColumnType.java

/**
 * Returns an object for a metadata value that is casted to the correct type
 * /* ww w.  j a v  a2s  . c  o  m*/
 * @throws MetaDataColumnException
 *             If an error occurred while attempting to cast the value
 */
public Object castValue(Object value) throws MetaDataColumnException {
    if (value == null) {
        return null;
    }

    try {
        switch (this) {
        case BOOLEAN:
            return (Boolean) new BooleanConverter().convert(Boolean.class, value);
        case NUMBER:
            BigDecimal number = (BigDecimal) new BigDecimalConverter().convert(BigDecimal.class, value);
            if (number.compareTo(MAX_NUMBER_VALUE) >= 0) {
                throw new Exception("Number " + String.valueOf(number)
                        + " is greater than or equal to the maximum allowed value of 10^16.");
            }
            return number;
        case STRING:
            String string = (String) new StringConverter().convert(String.class, value);
            if (string.length() > 255) {
                string = StringUtils.substring(string, 0, 255);
            }
            return string;
        case TIMESTAMP:
            return new DateParser().parse(value.toString());
        }
    } catch (Exception e) {
        throw new MetaDataColumnException(e);
    }

    throw new MetaDataColumnException("Unrecognized MetaDataColumnType");
}

From source file:org.apache.tajo.validation.MinValidator.java

@Override
protected <T> boolean validateInternal(T object) {
    boolean result = false;

    if (object != null) {
        if ((object instanceof Byte) || (object instanceof Short) || (object instanceof Integer)) {
            Integer objInteger = Integer.decode(object.toString());
            Integer minInteger = Integer.decode(minValue);
            result = objInteger.compareTo(minInteger) >= 0;
        } else if (object instanceof Long) {
            Long objLong = Long.decode(object.toString());
            Long minLong = Long.decode(minValue);
            result = objLong.compareTo(minLong) >= 0;
        } else if ((object instanceof Float) || (object instanceof Double)) {
            Double objDouble = Double.valueOf(object.toString());
            Double minDouble = Double.valueOf(minValue);
            result = objDouble.compareTo(minDouble) >= 0;
        } else if (object instanceof BigInteger) {
            BigInteger objInteger = (BigInteger) object;
            BigInteger minInteger = new BigInteger(minValue);
            result = objInteger.compareTo(minInteger) >= 0;
        } else if (object instanceof BigDecimal) {
            BigDecimal objDecimal = (BigDecimal) object;
            BigDecimal minDecimal = new BigDecimal(minValue);
            result = objDecimal.compareTo(minDecimal) >= 0;
        } else if (object instanceof String) {
            BigDecimal objDecimal = new BigDecimal((String) object);
            BigDecimal minDecimal = new BigDecimal(minValue);
            result = objDecimal.compareTo(minDecimal) >= 0;
        }//w ww.j a v  a  2  s.  c  o m
    } else {
        result = true;
    }

    return result;
}

From source file:com.github.fge.jsonschema.keyword.validator.common.MaximumValidator.java

@Override
protected void validateDecimal(final ProcessingReport report, final MessageBundle bundle, final FullData data)
        throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();
    final BigDecimal instanceValue = instance.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final int cmp = instanceValue.compareTo(decimalValue);

    if (cmp < 0)
        return;// ww  w.j  a  v a  2 s .co m

    if (cmp > 0) {
        report.error(newMsg(data, bundle, "err.common.maximum.tooLarge").putArgument(keyword, number)
                .putArgument("found", instance));
        return;
    }

    if (!exclusive)
        return;

    report.error(newMsg(data, bundle, "err.common.maximum.notExclusive").putArgument(keyword, number)
            .put("exclusiveMaximum", BooleanNode.TRUE));
}

From source file:com.github.fge.jsonschema.keyword.validator.common.MinimumValidator.java

@Override
protected void validateDecimal(final ProcessingReport report, final MessageBundle bundle, final FullData data)
        throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();
    final BigDecimal instanceValue = instance.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final int cmp = instanceValue.compareTo(decimalValue);

    if (cmp > 0)
        return;/*from  ww w  . j a va2s.  c  om*/

    if (cmp < 0) {
        report.error(newMsg(data, bundle, "err.common.minimum.tooSmall").putArgument(keyword, number)
                .putArgument("found", instance));
        return;
    }

    if (!exclusive)
        return;

    report.error(newMsg(data, bundle, "err.common.minimum.notExclusive").putArgument(keyword, number)
            .put("exclusiveMinimum", BooleanNode.TRUE));
}

From source file:org.eel.kitchen.jsonschema.keyword.MinimumKeywordValidator.java

@Override
protected void validateDecimal(final ValidationReport report, final JsonNode instance) {
    final BigDecimal instanceValue = instance.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final int cmp = instanceValue.compareTo(decimalValue);

    if (cmp > 0)
        return;/*from   w  ww . jav  a 2  s  . co m*/

    final Message.Builder msg = newMsg().addInfo(keyword, number).addInfo("found", instance);

    if (cmp < 0) {
        msg.setMessage("number is lower than the required minimum");
        report.addMessage(msg.build());
        return;
    }

    if (!exclusive)
        return;

    msg.addInfo("exclusiveMinimum", nodeFactory.booleanNode(true))
            .setMessage("number is not strictly greater than the required " + "minimum");
    report.addMessage(msg.build());
}