Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:com.realdolmen.rdfleet.soap.MileageUpdateLogicTest.java

private Car createCar() {
    Car car = new Car();
    car.setFunctionalLevel(2);/*from  w  w  w .j  a v a  2 s .  c o  m*/
    car.setMake("Audi");
    car.setModel("A1");
    car.setAmountDowngrade(BigDecimal.valueOf(2315.25));
    car.setFuelType(FuelType.DIESEL);
    car.setAmountUpgrade(BigDecimal.valueOf(0).setScale(2, RoundingMode.HALF_UP));
    car.setListPrice(BigDecimal.valueOf(25343.22));
    car.setTyreType(TyreType.ALUMINIUM);
    car.setTimeOfDeliveryInDays(Duration.ofDays(150));
    return car;
}

From source file:org.kuali.ole.select.document.web.struts.OleVendorCreditMemoAction.java

/**
 * @see org.kuali.ole.module.purap.document.web.struts.AccountsPayableActionBase#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from www  . j  av  a  2  s  .  c  om*/
@Override
public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    OleVendorCreditMemoForm creditForm = (OleVendorCreditMemoForm) form;
    OleVendorCreditMemoDocument creditDoc = (OleVendorCreditMemoDocument) creditForm.getDocument();
    if (creditDoc.getVendorDetail().getCurrencyType() != null) {
        if (creditDoc.getVendorDetail().getCurrencyType().getCurrencyType()
                .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
            currencyTypeIndicator = true;
        } else {
            currencyTypeIndicator = false;
        }
    }
    List<OleCreditMemoItem> item = creditDoc.getItems();

    if (!(creditDoc.getVendorDetail() == null
            || (creditDoc.getVendorDetail() != null && currencyTypeIndicator))) {

        LOG.debug("###########Foreign Currency Field Calculation###########");
        for (int i = 0; item.size() > i; i++) {
            OleCreditMemoItem items = (OleCreditMemoItem) creditDoc.getItem(i);
            Long id = creditDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
            Map documentNumberMap = new HashMap();
            documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
            BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
            List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(
                    OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
            Iterator iterator = exchangeRateList.iterator();
            if (iterator.hasNext()) {
                OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
                items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
                //creditDoc.setForeignVendorInvoiceAmount(creditDoc.getVendorInvoiceAmount().bigDecimalValue().multiply(tempOleExchangeRate.getExchangeRate()));
            }
            if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
                boolean rulePassed = getKualiRuleService()
                        .applyRules(new OleForeignCurrencyCreditMemoEvent(creditDoc, items));
                if (rulePassed) {
                    SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
                    if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
                        items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost()
                                .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4,
                                        RoundingMode.HALF_UP)));
                        items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue());
                    }
                }
            } else {
                if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) {

                    if (items.isAdditionalChargeUsd()) {
                        items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue());
                    } else {
                        items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue().divide(
                                items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP));

                    }
                }
            }
        }
    }
    creditDoc.setProrateBy(creditDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY
            : creditDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE
                    : creditDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR
                            : creditDoc.isNoProrate() ? OLEConstants.NO_PRORATE : null);
    if ((creditDoc.getProrateBy() != null) && (creditDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)
            || creditDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
            || creditDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
        LOG.debug("Calculation for ProrateItemSurcharge");
        getOleCreditMemoService().calculateCreditMemo(creditDoc);
    } else {
        for (OleCreditMemoItem items : item) {
            if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
                items.setItemSurcharge(BigDecimal.ZERO);
            }
        }
    }

    return super.calculate(mapping, form, request, response);
}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeTime.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;/*  w ww .java2s  .co m*/
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }

    // set date to 01.01.1970
    calendar = (Calendar) calendar.clone();
    calendar.set(1970, 0, 1);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.SECOND))[0],
                    bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.SECOND))[0],
                    charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, MINUTES) || StringUtils.equals(variant, MINUTES_SHORT)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1970, 0, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            long millisMidnight = calendar.getTimeInMillis();

            BigDecimal minutes = new BigDecimal(millis - millisMidnight);

            // milliseconds to minutes
            minutes = minutes.divide(BigDecimal.valueOf(1000 * 60), 0, RoundingMode.HALF_UP);

            // xxx
            minutes = minutes.divide(minuteMultiplier, 0, RoundingMode.HALF_UP);

            if (StringUtils.equals(variant, MINUTES_SHORT)) {
                result = charType.encode(minutes);
            } else {
                result = wordType.encode(minutes);
            }

        }
    }

    return result;
}

From source file:op.tools.SYSTools.java

public static void handleBigDecimalFocusLost(FocusEvent evt, BigDecimal min, BigDecimal max, BigDecimal def) {
    BigDecimal myBD;/*w ww.  ja v a  2 s  .c  o  m*/
    try {
        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:org.projectforge.business.gantt.GanttUtils.java

/**
 * @param node//w  ww .j  av a 2s  . c  o  m
 * @param depth For avoiding stack overflow errors
 * @return
 */
private static Date getCalculatedEndDate(final GanttTask node, final Set<Serializable> startDateSet,
        final Set<Serializable> endDateSet) {
    if (node == null) {
        return null;
    }
    if (node.getEndDate() != null) {
        return node.getEndDate();
    }
    if (node.isEndDateCalculated() == true) {
        return node.getCalculatedEndDate();
    }
    final int durationDays = node.getDuration() != null
            ? node.getDuration().setScale(0, RoundingMode.HALF_UP).intValue()
            : 0;
    if (node.getDuration() != null && node.getStartDate() != null) {
        final Date endDate = calculateDate(node.getStartDate(), durationDays);
        node.setCalculatedEndDate(endDate).setEndDateCalculated(true);
        if (log.isDebugEnabled() == true) {
            log.debug("calculated end date=" + endDate + " for: " + node);
        }
        return endDate;
    }
    if (endDateSet.contains(node.getId()) == true) {
        log.error("Circular reference detection (couldn't calculate end date: " + node);
        return null;
    } else {
        endDateSet.add(node.getId());
    }
    Date endDate = null;
    final GanttTask predecessor = node.getPredecessor();
    if (predecessor != null) {
        endDate = getPredecessorRelDate(node.getRelationType(), predecessor, startDateSet, endDateSet);
        if (endDate != null) {
            if (NumberHelper.isNotZero(node.getPredecessorOffset()) == true) {
                endDate = calculateDate(endDate, node.getPredecessorOffset());
            }
            if (node.getRelationType() != GanttRelationType.START_FINISH
                    && node.getRelationType() != GanttRelationType.FINISH_FINISH) {
                if (durationDays > 0) {
                    endDate = calculateDate(endDate, durationDays);
                }
            }
        }
    }
    if ((predecessor == null || (node.getRelationType() == null || node.getRelationType()
            .isIn(GanttRelationType.FINISH_FINISH, GanttRelationType.START_FINISH) == false))
            && node.getChildren() != null && node.getDuration() == null) {
        // There are children and the end date is not fix defined by a predecessor.
        for (final GanttTask child : node.getChildren()) {
            final Date date = getCalculatedEndDate(child, startDateSet, endDateSet);
            if (date != null && (endDate == null || date.after(endDate)) == true) {
                endDate = date;
            }
        }
    }
    if (endDate == null && node.getDuration() != null) {
        final Date calculatedStartDate = getCalculatedStartDate(node, startDateSet, endDateSet);
        if (calculatedStartDate != null) {
            endDate = calculateDate(calculatedStartDate, durationDays);
        }
    }
    node.setCalculatedEndDate(endDate).setEndDateCalculated(true);
    if (log.isDebugEnabled() == true) {
        log.debug("calculated end date=" + endDate + " for: " + node);
    }
    return endDate;
}

From source file:org.finra.herd.service.helper.BusinessObjectDefinitionHelper.java

/**
 * Processes the tags search score multiplier. Multiply all the tags search score.
 *
 * @param businessObjectDefinitionEntity the business object definition entity
 *///w  w w  .j av a 2s.c  o m
public void processTagSearchScoreMultiplier(
        final BusinessObjectDefinitionEntity businessObjectDefinitionEntity) {
    LOGGER.debug("processTagSearchScoreMultiplier " + businessObjectDefinitionEntity.getId() + " "
            + businessObjectDefinitionEntity.getBusinessObjectDefinitionTags());
    BigDecimal totalSearchScoreMultiplier = businessObjectDefinitionEntity.getBusinessObjectDefinitionTags()
            .stream().filter(item -> item.getTag().getSearchScoreMultiplier() != null).reduce(BigDecimal.ONE,
                    (bd, item) -> bd.multiply(item.getTag().getSearchScoreMultiplier()), BigDecimal::multiply)
            .setScale(3, RoundingMode.HALF_UP);
    businessObjectDefinitionEntity.setTagSearchScoreMultiplier(totalSearchScoreMultiplier);
}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeDate.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;//  w w w. ja  v a2s  .co  m
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }

    // set date to midnight
    calendar = (Calendar) calendar.clone();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;

            result = new byte[] { bcdType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    bcdType.encode(calendar.get(Calendar.MONTH) + 1)[0], bcdType.encode(dayOfWeek)[0],
                    bcdType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    bcdType.encode(calendar.get(Calendar.MONTH) + 1)[0],
                    bcdType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;

            result = new byte[] { charType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    charType.encode(calendar.get(Calendar.MONTH) + 1)[0], charType.encode(dayOfWeek)[0],
                    charType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    charType.encode(calendar.get(Calendar.MONTH) + 1)[0],
                    charType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, DAYS)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1900, 0, 1, 0, 0);
            long millis1900 = calendar.getTimeInMillis();

            BigDecimal days = new BigDecimal(millis - millis1900);
            days = days.divide(BigDecimal.valueOf(86400000), 0, RoundingMode.HALF_UP);

            result = wordType.encode(days);
        }
    }

    return result;
}

From source file:mx.edu.um.mateo.inventario.model.Entrada.java

public BigDecimal getSubtotal() {
    BigDecimal subtotal = total.subtract(iva).setScale(2, RoundingMode.HALF_UP);
    return subtotal;
}

From source file:com.vgi.mafscaling.Rescale.java

private void createControlPanel(JPanel dataPanel) {
    JPanel cntlPanel = new JPanel();
    GridBagConstraints gbl_ctrlPanel = new GridBagConstraints();
    gbl_ctrlPanel.insets = insets3;//from  ww  w .  ja  v a2s. co m
    gbl_ctrlPanel.anchor = GridBagConstraints.PAGE_START;
    gbl_ctrlPanel.fill = GridBagConstraints.HORIZONTAL;
    gbl_ctrlPanel.weightx = 1.0;
    gbl_ctrlPanel.gridx = 0;
    gbl_ctrlPanel.gridy = 0;
    dataPanel.add(cntlPanel, gbl_ctrlPanel);

    GridBagLayout gbl_cntlPanel = new GridBagLayout();
    gbl_cntlPanel.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
    gbl_cntlPanel.rowHeights = new int[] { 0, 0 };
    gbl_cntlPanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 };
    gbl_cntlPanel.rowWeights = new double[] { 0 };
    cntlPanel.setLayout(gbl_cntlPanel);

    NumberFormat doubleFmt = NumberFormat.getNumberInstance();
    doubleFmt.setGroupingUsed(false);
    doubleFmt.setMaximumIntegerDigits(1);
    doubleFmt.setMinimumIntegerDigits(1);
    doubleFmt.setMaximumFractionDigits(3);
    doubleFmt.setMinimumFractionDigits(1);
    doubleFmt.setRoundingMode(RoundingMode.HALF_UP);

    NumberFormat scaleDoubleFmt = NumberFormat.getNumberInstance();
    scaleDoubleFmt.setGroupingUsed(false);
    scaleDoubleFmt.setMaximumIntegerDigits(1);
    scaleDoubleFmt.setMinimumIntegerDigits(1);
    scaleDoubleFmt.setMaximumFractionDigits(8);
    scaleDoubleFmt.setMinimumFractionDigits(1);
    scaleDoubleFmt.setRoundingMode(RoundingMode.HALF_UP);

    GridBagConstraints gbc_cntlPanelLabel = new GridBagConstraints();
    gbc_cntlPanelLabel.anchor = GridBagConstraints.EAST;
    gbc_cntlPanelLabel.insets = new Insets(2, 3, 2, 1);
    gbc_cntlPanelLabel.gridx = 0;
    gbc_cntlPanelLabel.gridy = 0;

    GridBagConstraints gbc_cntlPanelInput = new GridBagConstraints();
    gbc_cntlPanelInput.anchor = GridBagConstraints.WEST;
    gbc_cntlPanelInput.insets = new Insets(2, 1, 2, 3);
    gbc_cntlPanelInput.gridx = 1;
    gbc_cntlPanelInput.gridy = 0;

    cntlPanel.add(new JLabel("New Max V"), gbc_cntlPanelLabel);

    newMaxVFmtTextBox = new JFormattedTextField(doubleFmt);
    newMaxVFmtTextBox.setColumns(7);
    newMaxVFmtTextBox.addPropertyChangeListener("value", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            Object source = e.getSource();
            if (source == newMaxVFmtTextBox)
                updateNewMafScale();
        }
    });
    cntlPanel.add(newMaxVFmtTextBox, gbc_cntlPanelInput);

    gbc_cntlPanelLabel.gridx += 2;
    cntlPanel.add(new JLabel("Min V"), gbc_cntlPanelLabel);

    minVFmtTextBox = new JFormattedTextField(doubleFmt);
    minVFmtTextBox.setColumns(7);
    minVFmtTextBox.addPropertyChangeListener("value", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            Object source = e.getSource();
            if (source == minVFmtTextBox)
                updateNewMafScale();
        }
    });
    gbc_cntlPanelInput.gridx += 2;
    cntlPanel.add(minVFmtTextBox, gbc_cntlPanelInput);

    gbc_cntlPanelLabel.gridx += 2;
    cntlPanel.add(new JLabel("Max Unchanged"), gbc_cntlPanelLabel);

    maxVUnchangedFmtTextBox = new JFormattedTextField(doubleFmt);
    maxVUnchangedFmtTextBox.setColumns(7);
    maxVUnchangedFmtTextBox.addPropertyChangeListener("value", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            Object source = e.getSource();
            if (source == maxVUnchangedFmtTextBox)
                updateNewMafScale();
        }
    });
    gbc_cntlPanelInput.gridx += 2;
    cntlPanel.add(maxVUnchangedFmtTextBox, gbc_cntlPanelInput);

    gbc_cntlPanelLabel.gridx += 2;
    cntlPanel.add(new JLabel("Mode deltaV"), gbc_cntlPanelLabel);

    modeDeltaVFmtTextBox = new JFormattedTextField(scaleDoubleFmt);
    modeDeltaVFmtTextBox.setColumns(7);
    modeDeltaVFmtTextBox.setEditable(false);
    modeDeltaVFmtTextBox.setBackground(new Color(210, 210, 210));
    gbc_cntlPanelInput.gridx += 2;
    cntlPanel.add(modeDeltaVFmtTextBox, gbc_cntlPanelInput);
}

From source file:org.sonar.api.measures.Measure.java

private double scaleValue(double value, int scale) {
    BigDecimal bd = BigDecimal.valueOf(value);
    return bd.setScale(scale, RoundingMode.HALF_UP).doubleValue();
}