Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.kuali.ole.module.purap.document.service.impl.OlePurapServiceImpl.java

public OleCreditMemoItem calculateForeignCurrency(OleCreditMemoItem oleCreditMemoItem) {
    if (oleCreditMemoItem.getItemForeignListPrice() != null
            && oleCreditMemoItem.getItemForeignDiscountType() != null) {
        if (oleCreditMemoItem.getItemForeignDiscount() == null) {
            oleCreditMemoItem.setItemForeignDiscount(new KualiDecimal(0));
        }//ww w. j  a  va 2  s .  com
        if (oleCreditMemoItem.getItemForeignDiscountType()
                .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
            BigDecimal calculatedForeignDiscountAmt = oleCreditMemoItem.getItemForeignDiscount()
                    .bigDecimalValue().multiply(new BigDecimal(0.01))
                    .multiply(oleCreditMemoItem.getItemForeignListPrice().bigDecimalValue());
            oleCreditMemoItem.setItemForeignDiscountAmt(new KualiDecimal(
                    calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
            oleCreditMemoItem.setItemForeignUnitCost(oleCreditMemoItem.getItemForeignListPrice()
                    .subtract(oleCreditMemoItem.getItemForeignDiscountAmt()));
            return oleCreditMemoItem;
        } else {
            oleCreditMemoItem.setItemForeignDiscountAmt(oleCreditMemoItem.getItemForeignDiscount());
            oleCreditMemoItem.setItemForeignUnitCost(oleCreditMemoItem.getItemForeignListPrice()
                    .subtract(oleCreditMemoItem.getItemForeignDiscount()));
            return oleCreditMemoItem;
        }
    } else {
        return oleCreditMemoItem;
    }
}

From source file:op.tools.SYSTools.java

public static void handleBigDecimalFocusLost(FocusEvent evt, BigDecimal min, BigDecimal max, BigDecimal def) {
    BigDecimal myBD;
    try {/*from www.j a  v a  2  s.c o m*/
        myBD = BigDecimal.valueOf(
                Double.parseDouble(assimilateDecimalSeparators(((JTextField) evt.getSource()).getText())));
    } catch (NumberFormatException ex) {
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.wrongentry")));
        myBD = def;
    }
    if (myBD.compareTo(min) < 0) {
        myBD = min;
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.entryTooSmall")));
    }
    if (myBD.compareTo(max) > 0) {
        myBD = max;
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.entryTooBig")));
    }

    ((JTextField) evt.getSource()).setText(myBD.setScale(2, RoundingMode.HALF_UP).toString());
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>BigDecimal</code>, by XML namespace and tag name, from an
 * XML Element. The children elements of <code>aElement</code> will be
 * searched for the specified <code>aNS</code> namespace URI and the
 * specified <code>aTagName</code>. The first XML element found will be
 * decoded and returned. If no element is found, <code>null</code> is
 * returned.//from   ww  w  .  ja v  a2s .  co m
 * 
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &ltdomain:create&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @return <code>BigDecimal</code> value if found; <code>null</code>
 *         otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static BigDecimal decodeBigDecimal(Element aElement, String aNS, String aTagName)
        throws EPPDecodeException {

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    BigDecimal retBigDecimal = null;
    if (theElm != null) {
        Node textNode = theElm.getFirstChild();

        // Element does have a text node?
        if (textNode != null) {

            String doubleValStr = textNode.getNodeValue();
            try {

                Double tempDouble = Double.valueOf(doubleValStr);
                retBigDecimal = new BigDecimal(tempDouble.doubleValue());
                retBigDecimal = retBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
            } catch (NumberFormatException e) {
                throw new EPPDecodeException("Can't convert value to Double: " + doubleValStr + e);
            }
        } else {
            throw new EPPDecodeException("Can't decode numeric value from non-existant text node");
        }
    }
    return retBigDecimal;
}

From source file:nl.strohalm.cyclos.entities.settings.LocalSettings.java

public BigDecimal round(final BigDecimal number) {
    if (number == null) {
        return null;
    } else {/*from w ww  . j ava 2 s  .c om*/
        return number.setScale(getPrecision().getValue(), RoundingMode.HALF_UP);
    }
}

From source file:nl.strohalm.cyclos.entities.settings.LocalSettings.java

public BigDecimal roundHighPrecision(final BigDecimal number) {
    if (number == null) {
        return null;
    } else {//  w  w w . j a  v  a  2  s  .c  om
        return number.setScale(getHighPrecision().getValue(), RoundingMode.HALF_UP);
    }
}

From source file:nl.strohalm.cyclos.entities.settings.LocalSettings.java

public BigDecimal truncate(final BigDecimal number) {
    if (number == null) {
        return null;
    } else {/*from ww  w  .j a va 2s. c o  m*/
        return number.setScale(getPrecision().getValue(), RoundingMode.FLOOR);
    }
}

From source file:org.apache.nifi.avro.AvroTypeUtil.java

@SuppressWarnings("unchecked")
private static Object convertToAvroObject(final Object rawValue, final Schema fieldSchema,
        final String fieldName, final Charset charset) {
    if (rawValue == null) {
        return null;
    }//from w  ww  . ja  va 2s.c om

    switch (fieldSchema.getType()) {
    case INT: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toInteger(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_DATE.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Date date = DataTypeUtils.toDate(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Duration duration = Duration.between(new Date(0L).toInstant(),
                    new Date(date.getTime()).toInstant());
            final long days = duration.toDays();
            return (int) days;
        } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Time time = DataTypeUtils.toTime(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Date date = new Date(time.getTime());
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            final long millisSinceMidnight = duration.toMillis();
            return (int) millisSinceMidnight;
        }

        return DataTypeUtils.toInteger(rawValue, fieldName);
    }
    case LONG: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toLong(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_TIME_MICROS.equals(logicalType.getName())) {
            final long longValue = getLongFromTimestamp(rawValue, fieldSchema, fieldName);
            final Date date = new Date(longValue);
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            return duration.toMillis() * 1000L;
        } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            Timestamp t = DataTypeUtils.toTimestamp(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName);
        } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalType.getName())) {
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName) * 1000L;
        }

        return DataTypeUtils.toLong(rawValue, fieldName);
    }
    case BYTES:
    case FIXED:
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) {
            final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType;
            final BigDecimal rawDecimal;
            if (rawValue instanceof BigDecimal) {
                rawDecimal = (BigDecimal) rawValue;

            } else if (rawValue instanceof Double) {
                rawDecimal = BigDecimal.valueOf((Double) rawValue);

            } else if (rawValue instanceof String) {
                rawDecimal = new BigDecimal((String) rawValue);

            } else if (rawValue instanceof Integer) {
                rawDecimal = new BigDecimal((Integer) rawValue);

            } else if (rawValue instanceof Long) {
                rawDecimal = new BigDecimal((Long) rawValue);

            } else {
                throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                        + rawValue.getClass() + " to a logical decimal");
            }
            // If the desired scale is different than this value's coerce scale.
            final int desiredScale = decimalType.getScale();
            final BigDecimal decimal = rawDecimal.scale() == desiredScale ? rawDecimal
                    : rawDecimal.setScale(desiredScale, BigDecimal.ROUND_HALF_UP);
            return new Conversions.DecimalConversion().toBytes(decimal, fieldSchema, logicalType);
        }
        if (rawValue instanceof byte[]) {
            return ByteBuffer.wrap((byte[]) rawValue);
        }
        if (rawValue instanceof String) {
            return ByteBuffer.wrap(((String) rawValue).getBytes(charset));
        }
        if (rawValue instanceof Object[]) {
            return AvroTypeUtil.convertByteArray((Object[]) rawValue);
        } else {
            throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                    + rawValue.getClass() + " to a ByteBuffer");
        }
    case MAP:
        if (rawValue instanceof Record) {
            final Record recordValue = (Record) rawValue;
            final Map<String, Object> map = new HashMap<>();
            for (final RecordField recordField : recordValue.getSchema().getFields()) {
                final Object v = recordValue.getValue(recordField);
                if (v != null) {
                    map.put(recordField.getFieldName(), v);
                }
            }

            return map;
        } else if (rawValue instanceof Map) {
            final Map<String, Object> objectMap = (Map<String, Object>) rawValue;
            final Map<String, Object> map = new HashMap<>(objectMap.size());
            for (final String s : objectMap.keySet()) {
                final Object converted = convertToAvroObject(objectMap.get(s), fieldSchema.getValueType(),
                        fieldName + "[" + s + "]", charset);
                map.put(s, converted);
            }
            return map;
        } else {
            throw new IllegalTypeConversionException(
                    "Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a Map");
        }
    case RECORD:
        final GenericData.Record avroRecord = new GenericData.Record(fieldSchema);

        final Record record = (Record) rawValue;
        for (final RecordField recordField : record.getSchema().getFields()) {
            final Object recordFieldValue = record.getValue(recordField);
            final String recordFieldName = recordField.getFieldName();

            final Field field = fieldSchema.getField(recordFieldName);
            if (field == null) {
                continue;
            }

            final Object converted = convertToAvroObject(recordFieldValue, field.schema(),
                    fieldName + "/" + recordFieldName, charset);
            avroRecord.put(recordFieldName, converted);
        }
        return avroRecord;
    case UNION:
        return convertUnionFieldValue(rawValue, fieldSchema,
                schema -> convertToAvroObject(rawValue, schema, fieldName, charset), fieldName);
    case ARRAY:
        final Object[] objectArray = (Object[]) rawValue;
        final List<Object> list = new ArrayList<>(objectArray.length);
        int i = 0;
        for (final Object o : objectArray) {
            final Object converted = convertToAvroObject(o, fieldSchema.getElementType(),
                    fieldName + "[" + i + "]", charset);
            list.add(converted);
            i++;
        }
        return list;
    case BOOLEAN:
        return DataTypeUtils.toBoolean(rawValue, fieldName);
    case DOUBLE:
        return DataTypeUtils.toDouble(rawValue, fieldName);
    case FLOAT:
        return DataTypeUtils.toFloat(rawValue, fieldName);
    case NULL:
        return null;
    case ENUM:
        return new GenericData.EnumSymbol(fieldSchema, rawValue);
    case STRING:
        return DataTypeUtils.toString(rawValue, (String) null, charset);
    }

    return rawValue;
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

/**
 * @param demandDetailSet/*from  w  w w . ja  v a2 s  .  c  o m*/
 * @param installment
 * @param totalDemandAmount
 * @return
 */
private EgDemand createDemand(final Set<EgDemandDetails> demandDetailSet, final Installment installment,
        final BigDecimal totalDemandAmount) {
    final EgDemand egDemand = new EgDemand();
    egDemand.setEgInstallmentMaster(installment);
    egDemand.getEgDemandDetails().addAll(demandDetailSet);
    egDemand.setIsHistory("N");
    egDemand.setCreateDate(new Date());
    egDemand.setBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));
    egDemand.setModifiedDate(new Date());
    return egDemand;
}

From source file:jp.terasoluna.fw.web.taglib.DecimalTag.java

/**
 * ^O]Jn?\bh?B//from www .  jav  a  2  s  .c  o m
 *
 * @return ???w?B? <code>SKIP_BODY</code>
 * @throws JspException JSPO
 */
@Override
public int doStartTag() throws JspException {

    Object value = this.value;
    if (value == null) {
        // bean???Av?beanbNAbv
        // ???A^?[
        if (ignore) {
            if (TagUtil.lookup(pageContext, name, scope) == null) {
                return SKIP_BODY; // ?o
            }
        }

        // v?v?peBlbNAbv
        value = TagUtil.lookup(pageContext, name, property, scope);
        if (value == null) {
            return SKIP_BODY; // ?o
        }
    }

    // v?peBlString^xBigDecimal
    BigDecimal bd = null;
    if (value instanceof String) {
        String trimed = StringUtil.rtrim((String) value);
        if ("".equals(trimed)) {
            return SKIP_BODY; //  ?o
        }
        bd = new BigDecimal(trimed);
    } else if (value instanceof BigDecimal) {
        bd = (BigDecimal) value;
    } else {
        return SKIP_BODY; // ?o
    }

    // ??_?w??
    if (scale >= 0) {
        // round???[h?s?i???l?j
        if (round != null) {
            if ("ROUND_FLOOR".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_FLOOR);
            } else if ("ROUND_CEILING".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_CEILING);
            } else if ("ROUND_HALF_UP".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
            } else {
                log.error("Please set a rounding mode");
                throw new IllegalArgumentException("Please set a rounding mode");
            }
        } else {
            bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
    }

    // tH?[}bg
    DecimalFormat df = new DecimalFormat(pattern);
    String output = df.format(bd);

    if (id != null) {
        // idw?AXNveBO?p
        // y?[WXR?[vZbg?B
        pageContext.setAttribute(id, output);
    } else {
        // idw?Av?peBlC^vg
        // ?BK?tB^?B
        if (filter) {
            TagUtil.write(pageContext, TagUtil.filter(output));
        } else {
            TagUtil.write(pageContext, output);
        }
    }

    return SKIP_BODY;
}

From source file:org.kuali.kfs.module.bc.document.service.impl.SalarySettingServiceImpl.java

/**
 * @see org.kuali.kfs.module.bc.document.service.SalarySettingService#calculateFteQuantity(java.lang.Integer, java.lang.Integer,
 *      java.math.BigDecimal)/*  w  ww  .  j  a  va 2 s.  c o  m*/
 */
public BigDecimal calculateFteQuantity(Integer payMonth, Integer fundingMonth,
        BigDecimal requestedTimePercent) {
    LOG.debug("calculateFteQuantity() start");

    if (payMonth == null || fundingMonth == null || requestedTimePercent == null) {
        return BigDecimal.ZERO;
    }

    BigDecimal payMonthAsDecimal = BigDecimal.valueOf(payMonth);
    BigDecimal fundingMonthAsDecimal = BigDecimal.valueOf(fundingMonth);
    BigDecimal fundingMonthPercent = fundingMonthAsDecimal.divide(payMonthAsDecimal, 5,
            BigDecimal.ROUND_HALF_UP);

    BigDecimal fteQuantity = requestedTimePercent.multiply(fundingMonthPercent)
            .divide(KFSConstants.ONE_HUNDRED.bigDecimalValue());

    return fteQuantity.setScale(5, BigDecimal.ROUND_HALF_UP);
}