Java Code Examples for java.math.BigDecimal#ROUND_CEILING

The following examples show how to use java.math.BigDecimal#ROUND_CEILING . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
 * Truncate a decimal value to the given number of decimal places.
 * @param numeric the decimal number to truncate.
 * @param truncPlaces the integer number of decimal places to truncate. If truncPlaces is positive,
 *                   numeric is truncated (zeroed) starting from truncPlaces + 1 places to the left
 *                   of the decimal point.  If it's negative, numeric is truncated starting from
 *                   truncPlaces places to the left of the decimal point.
 * @return the truncated value.
 * @throws StandardException
public static NumberDataValue truncDecimal(DataValueDescriptor numeric, DataValueDescriptor truncPlaces)
    throws StandardException {

    // Gotta clone here because ref changes value when both trunc value and column are selected
    // For example, if select trunc(n, 1), n from trunctest, n also displays truncated value
    NumberDataValue returnValue = (NumberDataValue) numeric.cloneValue(false);
    double valueToTrunc = returnValue.getDouble();
    int roundingMode = BigDecimal.ROUND_FLOOR;
    if (valueToTrunc < 1) {
        // short circuit if we know answer is zero (valueToTrunc<1 && valueToTrunc>=0 && truncPlaces<0)
        if (valueToTrunc >= 0 && truncPlaces.getInt() <= 0) {
            returnValue.setBigDecimal(new BigDecimal(0));
            return returnValue;
        roundingMode = BigDecimal.ROUND_CEILING;
    // Change the scale on the clone
    Object value = numeric.getObject();
    BigDecimal y;
    if (value == null || ! (value instanceof BigDecimal)) {
        // could be integer.  trunc as decimal.
        y = new BigDecimal(String.valueOf(valueToTrunc)).setScale(truncPlaces.getInt(), roundingMode);
    } else {
        y = ((BigDecimal)value).setScale(truncPlaces.getInt(), roundingMode);
    // BigDecimal#precision() has the side effect of setting the precision. Needed since we've changed it.
    int precision = y.precision();
    return returnValue;