Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_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:org.egov.egf.web.actions.budget.BudgetSearchAction.java

public BigDecimal divideAndRoundStrToBigDec(final String amountStr) {
    BigDecimal value = new BigDecimal(amountStr);
    value = value.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
    return value;
}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

/**
 * A - ( A * B / 100 )//from   www  .  ja  v a  2 s  . c o  m
 *  
 * @param metaA
 * @param dataA
 * @param metaB
 * @param dataB
 * @return
 * @throws KettleValueException
 */
public static Object percent2(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB)
        throws KettleValueException {
    if (dataA == null || dataB == null)
        return null;

    switch (metaA.getType()) {
    case ValueMetaInterface.TYPE_NUMBER:
        return new Double(metaA.getNumber(dataA).doubleValue()
                - (100.0 * metaA.getNumber(dataA).doubleValue() / metaB.getNumber(dataB).doubleValue()));
    case ValueMetaInterface.TYPE_INTEGER:
        return new Long(metaA.getInteger(dataA).longValue()
                - (100 * metaA.getInteger(dataA).longValue() / metaB.getInteger(dataB).longValue()));
    case ValueMetaInterface.TYPE_BIGNUMBER:
        BigDecimal percentTotal = metaA.getBigNumber(dataA).multiply(new BigDecimal(100))
                .divide(metaB.getBigNumber(dataB), BigDecimal.ROUND_HALF_UP);
        return metaA.getBigNumber(dataA).subtract(percentTotal);

    default:
        throw new KettleValueException("The 'percent2' function only works on numeric data");
    }
}

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Method is executed on update trigger for the rate field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/*from   w w w .ja v a 2  s  .c o  m*/
 * @throws EFapsException on error
 */
public Return update4Rate(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();

    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ONE : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);

        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Rate.ParseException", e);
    }
    return retVal;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

protected LayerPriceComposition calculateLayerPriceComposition(DataWrapper dw, ExtLayerCalculator lc,
        String spAbbr, String layerName) throws Exception {
    String operation = dw.getOperation();
    if (operation == null) {
        log.error("Operation can not be null");
        throw new Exception("Operation can not be null");
    }/*  ww w. j a  v a 2 s  . co m*/
    String projection = dw.getOgcrequest().getParameter(OGCConstants.WFS_PARAM_SRSNAME); // todo klopt dit?
    /*
     * De srs parameter word nu alleen gevult met null. Hier moet misschien
     * nog naar gekeken worden, maar nu werk het zo wel.
     */
    BigDecimal scale = (new BigDecimal(dw.getOgcrequest().calcScale())).setScale(2, BigDecimal.ROUND_HALF_UP);
    int planType = LayerPricing.PAY_PER_REQUEST;
    String service = OGCConstants.WFS_SERVICE_WFS;

    return lc.calculateLayerComplete(spAbbr, layerName, new Date(), projection, scale, new BigDecimal("1"),
            planType, service, operation);
}

From source file:org.egov.egf.web.actions.budget.BudgetSearchAction.java

public String divideAndRoundBigDecToString(final BigDecimal amount) {
    BigDecimal value = amount;//from  w  w w.ja  va 2  s. c  o  m
    value = value.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
    return value.toString();
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Rounds the given non-negative value to the "nearest" integer. Nearest is
 * determined by the rounding method specified. Rounding methods are defined
 * in {@link BigDecimal}.//from ww w  .j av a2  s .  co m
 *
 * @param unscaled Value to round.
 * @param sign Sign of the original, scaled value.
 * @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
 * @return the rounded value.
 * @throws MathArithmeticException if an exact operation is required but result is not exact
 * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
 * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
 */
private static double roundUnscaled(double unscaled, double sign, int roundingMethod)
        throws MathArithmeticException, MathIllegalArgumentException {
    switch (roundingMethod) {
    case BigDecimal.ROUND_CEILING:
        if (sign == -1) {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        } else {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_DOWN:
        unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        break;
    case BigDecimal.ROUND_FLOOR:
        if (sign == -1) {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        } else {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_HALF_DOWN: {
        unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_HALF_EVEN: {
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else if (fraction < 0.5) {
            unscaled = FastMath.floor(unscaled);
        } else {
            // The following equality test is intentional and needed for rounding purposes
            if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even
                unscaled = FastMath.floor(unscaled);
            } else { // odd
                unscaled = FastMath.ceil(unscaled);
            }
        }
        break;
    }
    case BigDecimal.ROUND_HALF_UP: {
        unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction >= 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_UNNECESSARY:
        if (unscaled != FastMath.floor(unscaled)) {
            throw new MathArithmeticException();
        }
        break;
    case BigDecimal.ROUND_UP:
        unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        break;
    default:
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod,
                "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR",
                BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN",
                BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY",
                BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP);
    }
    return unscaled;
}

From source file:com.aimluck.eip.project.ProjectTaskSimpleSelectData.java

/**
 * ResultData???? <BR>//from ww w . j  ava  2s.  co  m
 * 
 * @param record
 *          
 * @return ResultData
 */
@Override
protected Object getResultData(EipTProjectTask record) {
    ProjectTaskResultData data = ProjectUtils.getProjectTaskResultData(record);
    Integer taskId = (int) data.getTaskId().getValue();

    // ?
    int cntChild = ProjectUtils.getCountChildrenTask(taskId);

    // ??2??true
    // ??
    data.setHasChildren(cntChild >= 2);

    // ?
    data.setHasChildrenForForm(cntChild > 0);

    // ?
    int lapsedDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(Calendar.getInstance().getTime()));
    // 
    int taskDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(record.getEndPlanDate()));
    data.setPlanTerm(taskDays);

    if (lapsedDays > taskDays) {
        // ???
        lapsedDays = taskDays;
    }

    // ?
    data.setPlanProgressRate(ProjectUtils.getPlanWorkload(lapsedDays, taskDays));

    // 
    List<ProjectTaskMemberResultData> memberList = data.getMemberList();
    BigDecimal workload = BigDecimal.valueOf(0);
    workload = workload.setScale(1);
    for (int i = 0; i < memberList.size(); i++) {
        ProjectTaskMemberResultData member = memberList.get(i);
        workload = workload.add(member.getWorkload());
    }
    data.setWorkload(workload);

    // 
    BigDecimal forecastWorkload = BigDecimal.valueOf(0);
    if (data.getProgressRate().getValue() != 0) {
        forecastWorkload = workload.multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(data.getProgressRate().getValue()), 2, BigDecimal.ROUND_HALF_UP);
    }
    data.setForecastWorkload(forecastWorkload);

    // 
    data.setIndentFlg(indentFlg);

    return data;
}

From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java

/**
 * Returns the consolidated collections for single day and between the 2
 * dates/*from  w w  w.  j  a  va 2s . c  o m*/
 *
 * @param collectionDashBoardRequest
 * @param fromDate
 * @param toDate
 * @param cityName
 * @return BigDecimal
 */
public BigDecimal getCollectionBetweenDates(final CollectionDashBoardRequest collectionDashBoardRequest,
        final Date fromDate, final Date toDate, final String cityName, final List<String> serviceDetails,
        final boolean isWard) {
    final Long startTime = System.currentTimeMillis();
    BoolQueryBuilder boolQuery = prepareWhereClause(collectionDashBoardRequest);
    boolQuery = boolQuery
            .filter(QueryBuilders.rangeQuery(RECEIPT_DATE).gte(DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                    .lte(DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
            .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));
    if (StringUtils.isNotBlank(cityName))
        if (!isWard)
            boolQuery = boolQuery.filter(QueryBuilders.matchQuery(CITY_NAME, cityName));
        else
            boolQuery = boolQuery.filter(QueryBuilders.matchQuery(REVENUE_WARD, cityName));
    if (!serviceDetails.isEmpty())
        boolQuery = boolQuery.filter(QueryBuilders.termsQuery(BILLING_SERVICE, serviceDetails));

    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(COLLECTION_INDEX_NAME)
            .withQuery(boolQuery).addAggregation(AggregationBuilders.sum(COLLECTIONTOTAL).field(TOTAL_AMOUNT))
            .build();

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Sum aggr = collAggr.get(COLLECTIONTOTAL);
    final Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by getCollectionBetweenDates() is : " + timeTaken + MILLISECS);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:org.diretto.web.richwebclient.view.sections.UploadSection.java

/**
 * Uploads the currently processed file.
 * /*ww w .j  ava2  s . c o  m*/
 * @param uploadSettings The {@code UploadSettings} of the file
 * @param filesWithSameSettings A {@code List} with the names of the files
 *        which should get the given {@code UploadSettings} as presetting
 */
public void upload(final UploadSettings uploadSettings, List<String> filesWithSameSettings) {
    final FileInfo fileInfo = currentFile;

    settings.put(fileInfo.getName(), uploadSettings);

    for (String fileName : filesWithSameSettings) {
        preSettings.put(fileName, uploadSettings);
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            ProgressIndicator progressIndicator = multipleUpload.upload(fileInfo);

            synchronized (application) {
                VerticalLayout uploadBoxLayout = new VerticalLayout();
                mainLayout.addComponent(uploadBoxLayout);

                HorizontalLayout fileInfoLayout = new HorizontalLayout();
                uploadBoxLayout.addComponent(fileInfoLayout);

                Label nameLabel = StyleUtils.getLabelBold(fileInfo.getName());
                fileInfoLayout.addComponent(nameLabel);
                fileInfoLayout.addComponent(StyleUtils.getLabelSmallHTML("&nbsp;&nbsp;&nbsp;"));
                fileInfoLayout.setComponentAlignment(nameLabel, Alignment.MIDDLE_LEFT);

                BigDecimal fileSize = new BigDecimal((((double) fileInfo.getSize()) / 1000000.0d));
                fileSize = fileSize.setScale(2, BigDecimal.ROUND_HALF_UP);

                Label typeSizeLabel = StyleUtils.getLabelSmallHTML(
                        fileInfo.getType() + "&nbsp;&nbsp;--&nbsp;&nbsp;" + fileSize.toPlainString() + " MB");
                fileInfoLayout.addComponent(typeSizeLabel);
                fileInfoLayout.setComponentAlignment(typeSizeLabel, Alignment.MIDDLE_LEFT);

                uploadBoxLayout.addComponent(StyleUtils.getVerticalSpace("100%", "8px"));

                uploadBoxLayout.addComponent(progressIndicator);

                uploadBoxLayout.addComponent(StyleUtils.getVerticalSpace("100%", "8px"));

                HorizontalLayout resultLayout = new HorizontalLayout();
                uploadBoxLayout.addComponent(resultLayout);

                Label uploadedLabel = StyleUtils.getLabelSmallHTML("Uploaded:&nbsp;");
                resultLayout.addComponent(uploadedLabel);
                resultLayout.setComponentAlignment(uploadedLabel, Alignment.MIDDLE_LEFT);

                Embedded uploadedEmbedded = new Embedded(null, ResourceUtils.RUNO_ICON_32_GLOBE_RESOURCE);
                uploadedEmbedded.addStyleName("image-opacity-65");
                uploadedEmbedded.setType(Embedded.TYPE_IMAGE);
                uploadedEmbedded.setImmediate(true);
                uploadedEmbedded.setWidth("22px");
                uploadedEmbedded.setHeight("22px");
                resultLayout.addComponent(uploadedEmbedded);

                uploadedEmbeddeds.put(fileInfo, uploadedEmbedded);

                resultLayout.addComponent(StyleUtils.getLabelSmallHTML("&nbsp;&nbsp;&nbsp;"));

                Label publishedLabel = StyleUtils.getLabelSmallHTML("Published:&nbsp;");
                resultLayout.addComponent(publishedLabel);
                resultLayout.setComponentAlignment(publishedLabel, Alignment.MIDDLE_LEFT);

                Embedded publishedEmbedded = new Embedded(null, ResourceUtils.RUNO_ICON_32_GLOBE_RESOURCE);
                publishedEmbedded.addStyleName("image-opacity-65");
                publishedEmbedded.setType(Embedded.TYPE_IMAGE);
                publishedEmbedded.setImmediate(true);
                publishedEmbedded.setWidth("22px");
                publishedEmbedded.setHeight("22px");
                resultLayout.addComponent(publishedEmbedded);

                publishedEmbeddeds.put(fileInfo, publishedEmbedded);

                mainLayout.addComponent(StyleUtils.getVerticalSpace("100%", "5px"));

                requestRepaint();
            }
        }
    }).start();

    handleNextFile();
}

From source file:org.efaps.esjp.accounting.transaction.Transaction_Base.java

/**
 * @param _oldValue old Value//from  w w  w.  j  av a 2s  . co m
 * @param _oldRate old Rate
 * @param _newRate new Rate
 * @return new Value
 */
protected BigDecimal getNewValue(final BigDecimal _oldValue, final BigDecimal _oldRate,
        final BigDecimal _newRate) {
    BigDecimal ret = BigDecimal.ZERO;
    if (_oldValue.compareTo(BigDecimal.ZERO) != 0) {
        ret = _oldValue.multiply(_oldRate).divide(_newRate, BigDecimal.ROUND_HALF_UP).setScale(2,
                BigDecimal.ROUND_HALF_UP);
    }
    return ret;
}