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.cryptomath.CryptoMath.java

public static BigDecimal inverse(final BigDecimal value) {
    if (isNotZero(value)) {
        return BigDecimal.ONE.setScale(MAX_SCALE_FOR_INVERSE).divide(value, BigDecimal.ROUND_HALF_UP);
        //       return BigDecimal.ONE.setScale(MAX_SCALE_FOR_INVERSE).divide(value);
    }//from  www  . j  av a2 s.  c o  m
    return null;
}

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

/**
 * Inits the link html.// w  w  w. j  av a2s  .  c  o m
 *
 * @throws EFapsException on error
 */
protected void initLinkHtml() throws EFapsException {
    if (this.linkCreditHtml == null && getInstance() != null && getInstance().isValid()) {
        this.linkCreditHtml = new StringBuilder();
        this.linkDebitHtml = new StringBuilder();
        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, getInstance());
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator,
                CIAccounting.Account2AccountAbstract.Denominator, CIAccounting.Account2AccountAbstract.Config);
        final SelectBuilder sel = SelectBuilder.get().linkto(CIAccounting.Account2AccountAbstract.ToAccountLink)
                .attribute(CIAccounting.AccountAbstract.Name);
        multi.addSelect(sel);
        multi.execute();
        final StringBuilder tmpBldr = new StringBuilder();
        while (multi.next()) {
            final String to = multi.<String>getSelect(sel);
            final Collection<Accounting.Account2AccountConfig> configs = multi
                    .getAttribute(CIAccounting.Account2AccountAbstract.Config);
            final Integer numerator = multi
                    .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator);
            final Integer denominator = multi
                    .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator);
            final BigDecimal percent = new BigDecimal(numerator)
                    .divide(new BigDecimal(denominator), BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
            final Instance tmpInstance = multi.getCurrentInstance();
            if (configs != null && configs.contains(Accounting.Account2AccountConfig.DEACTIVATABLE)) {
                tmpBldr.append("<input type='checkbox' name='acc2acc").append(getPostFix())
                        .append("' checked='checked' value='").append(tmpInstance.getOid()).append("'/>");
            }
            tmpBldr.append(DBProperties.getFormatedDBProperty(
                    Transaction.class.getName() + ".LinkString4" + tmpInstance.getType().getName(),
                    new Object[] { percent, StringEscapeUtils.escapeEcmaScript(to) }));
            if (configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT)) {
                this.linkDebitHtml = tmpBldr;
            }
            if (configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT)) {
                this.linkCreditHtml = tmpBldr;
            }
        }
    }
}

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

/**
 * @param dmdAmount/*from   w w  w  .  j  av a  2 s .co m*/
 * @param egDemandReason
 * @param amtCollected
 * @return
 */
public EgDemandDetails createDemandDetails(final BigDecimal dmdAmount, final EgDemandReason egDemandReason,
        final BigDecimal amtCollected) {
    return EgDemandDetails.fromReasonAndAmounts(dmdAmount.setScale(0, BigDecimal.ROUND_HALF_UP), egDemandReason,
            amtCollected);
}

From source file:com.whatlookingfor.common.utils.StringUtils.java

/**
 * ??????//from   w  w  w  .  j  a  va2  s  .  co  m
 *
 * @param v     ??
 * @param scale ????
 * @return ??
 */
public static double round(double v, int scale) {
    if (scale < 0) {
        throw new IllegalArgumentException("The scale must be a positive integer or zero");
    }
    BigDecimal b = new BigDecimal(Double.toString(v));
    BigDecimal one = new BigDecimal("1");
    return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

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

/**
 * Executed on update event of the currency field.
 * @param _parameter    parameter as passed from the eFaps API
 * @return  list of maps as needed by the update event
 * @throws EFapsException on error/*from w w w.ja  v  a  2 s .  c om*/
 */
public Return update4Currency(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] currIds = _parameter.getParameterValues("rateCurrencyLink_" + postfix);
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);

        final int pos = getSelectedRow(_parameter);

        final ExchangeConfig exConf = getExchangeConfig(_parameter, null);
        final DateTime date;
        switch (exConf) {
        case DOCDATEPURCHASE:
        case DOCDATESALE:
            final Instance docInst = Instance.get(_parameter.getParameterValues("docLink_" + postfix)[pos]);
            if (InstanceUtils.isValid(docInst)) {
                final PrintQuery print = CachedPrintQuery.get4Request(docInst);
                print.addAttribute(CIERP.DocumentAbstract.Date);
                print.execute();
                date = print.getAttribute(CIERP.DocumentAbstract.Date);
            } else {
                final String dateStr = _parameter.getParameterValue("date_eFapsDate");
                date = DateUtil.getDateFromParameter(dateStr);
            }
            break;
        case TRANSDATESALE:
        case TRANSDATEPURCHASE:
        default:
            final String dateStr = _parameter.getParameterValue("date_eFapsDate");
            date = DateUtil.getDateFromParameter(dateStr);
            break;
        }

        final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf)
                || ExchangeConfig.DOCDATESALE.equals(exConf);

        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);
        final RateInfo rate = evaluateRate(_parameter, periodInstance, date,
                Instance.get(CIERP.Currency.getType(), currIds[pos]));
        final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI()
                : rate.getFormatter().getFrmt4RateUI();
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amountRate = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);

        final BigDecimal sum = getSum4UI(_parameter, postfix, pos, rate);
        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 List<Map<String, String>> list = new ArrayList<>();
        final Map<String, String> map = new HashMap<>();
        map.put("rate_" + postfix, sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt());
        map.put("rate_" + postfix + RateUI.INVERTEDSUFFIX, "" + rate.isInvert());
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix, formater.format(amountRate.setScale(12)
                .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        ret.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * API returns the current year total demand from Property Tax index
 *
 * @return BigDecimal/*from   w  w w .  j a v  a  2  s.  c  om*/
 */
public BigDecimal getTotalDemand() {
    final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
            .filter(QueryBuilders.rangeQuery(TOTAL_DEMAND).from(0).to(null))
            .filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
            .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));
    final SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(PROPERTY_TAX_INDEX_NAME)
            .withQuery(boolQuery).addAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND))
            .build();

    final Aggregations aggregations = elasticsearchTemplate.query(searchQuery,
            response -> response.getAggregations());

    final Sum aggr = aggregations.get(TOTALDEMAND);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:org.kuali.kfs.module.ar.document.validation.impl.CustomerCreditMemoDocumentRule.java

public boolean checkIfCustomerCreditMemoQtyAndCustomerCreditMemoItemAmountValid(
        CustomerCreditMemoDetail customerCreditMemoDetail, BigDecimal unitPrice) {
    KualiDecimal creditAmount = customerCreditMemoDetail.getCreditMemoItemTotalAmount();
    BigDecimal creditQuantity = customerCreditMemoDetail.getCreditMemoItemQuantity();

    // if unit price is zero, leave this validation, as it will cause an exception below by attempting to divide by zero
    if (unitPrice.compareTo(BigDecimal.ZERO) == 0) {
        // no need to report error, because it is already recorded by another validation check.
        return false;
    }//ww w  .  jav  a2 s  .  c o  m

    // determine the expected exact total credit memo quantity, based on actual credit amount entered
    BigDecimal expectedCreditQuantity = creditAmount.bigDecimalValue().divide(unitPrice,
            ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP);

    // return false if the expected quantity is 0 while the actual quantity is not
    if (expectedCreditQuantity.compareTo(BigDecimal.ZERO) == 0
            && creditQuantity.compareTo(BigDecimal.ZERO) != 0) {
        return false;
    }

    // determine the deviation percentage that the actual creditQuantity has from expectedCreditQuantity
    BigDecimal deviationPercentage = creditQuantity.subtract(expectedCreditQuantity)
            .divide(expectedCreditQuantity, ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP).abs();

    // only allow a certain deviation of creditQuantity from the expectedCreditQuantity
    boolean validFlag = deviationPercentage.compareTo(ALLOWED_QTY_DEVIATION) < 1;

    if (!validFlag) {
        GlobalVariables.getMessageMap().putError(
                ArPropertyConstants.CustomerCreditMemoDocumentFields.CREDIT_MEMO_ITEM_QUANTITY,
                ArKeyConstants.ERROR_CUSTOMER_CREDIT_MEMO_DETAIL_INVALID_DATA_INPUT);
        GlobalVariables.getMessageMap().putError(
                ArPropertyConstants.CustomerCreditMemoDocumentFields.CREDIT_MEMO_ITEM_TOTAL_AMOUNT,
                ArKeyConstants.ERROR_CUSTOMER_CREDIT_MEMO_DETAIL_INVALID_DATA_INPUT);
    }
    return validFlag;
}

From source file:com.dsi.ant.antplus.pluginsampler.geocache.Dialog_GeoDeviceDetails.java

protected void refreshData() {
    //Set data display with current values
    if (deviceData.programmableData.identificationString != null)
        textView_IdString.setText(String.valueOf(deviceData.programmableData.identificationString));
    if (deviceData.programmableData.PIN != null)
        textView_PIN.setText(String.valueOf(deviceData.programmableData.PIN));
    if (deviceData.programmableData.latitude != null)
        textView_Latitude.setText(/*from www  . jav a2s  .  c  om*/
                String.valueOf(deviceData.programmableData.latitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    if (deviceData.programmableData.longitude != null)
        textView_Longitude.setText(
                String.valueOf(deviceData.programmableData.longitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    if (deviceData.programmableData.hintString != null)
        textView_HintString.setText(String.valueOf(deviceData.programmableData.hintString));
    if (deviceData.programmableData.lastVisitTimestamp != null) {
        DateFormat df = DateFormat.getDateTimeInstance();
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        textView_LastVisit.setText(df.format(deviceData.programmableData.lastVisitTimestamp.getTime()));
    }
    if (deviceData.programmableData.numberOfVisits != null)
        textView_NumVisits.setText(String.valueOf(deviceData.programmableData.numberOfVisits));

    textView_HardwareVer.setText(String.valueOf(deviceData.hardwareRevision));
    textView_ManfID.setText(String.valueOf(deviceData.manufacturerID));
    textView_ModelNum.setText(String.valueOf(deviceData.modelNumber));
    textView_SoftwareVer.setText(String.valueOf(deviceData.softwareRevision));
    textView_SerialNum.setText(String.valueOf(deviceData.serialNumber));
    textView_BatteryVoltage.setText(String.valueOf(deviceData.batteryVoltage));
    textView_BatteryStatus.setText(deviceData.batteryStatus.toString());
    textView_OperatingTime.setText(String.valueOf(deviceData.cumulativeOperatingTime));
    textView_OperatingTimeResolution.setText(String.valueOf(deviceData.cumulativeOperatingTimeResolution));
}

From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java

public BigDecimal get(BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
        throw new IllegalArgumentException();
    }//from   ww w .  j  av  a 2  s  .  c  o m

    BigDecimal initialGuess = getInitialApproximation(n);
    trace("Initial guess " + initialGuess.toString());
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
        lastGuess = guess;
        guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
        guess = guess.add(lastGuess);
        guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
        trace("Next guess " + guess.toString());
        error = n.subtract(guess.multiply(guess));
        if (++iterations >= maxIterations) {
            more = false;
        } else if (lastGuess.equals(guess)) {
            more = error.abs().compareTo(ONE) >= 0;
        }
    }
    return guess;

}

From source file:org.kalypso.model.wspm.pdb.internal.gaf.Gaf2Db.java

/**
 * Calculates the width of a point if it is not set in the gaf file.<br/>
 * For PP points, it is just the distance to the first point.<br/>
 * For non-pp points, it is the station of the point projected to the pp-line.
 *///from ww w  .ja v  a 2  s . c  om
private BigDecimal getOrCalculatePoint(final GafPart gafPart, final GafPoint gafPoint,
        final GafPart projectionPart) {
    final BigDecimal width = gafPoint.getWidth();
    if (width != null)
        return width;

    final com.vividsolutions.jts.geom.Point location = gafPoint.getPoint();
    if (GafKind.P.equals(gafPart.getKind()) || projectionPart == null) {
        return calculateWidthFromDistance(gafPart, location);
    } else {
        final Geometry line = projectionPart.getLine(m_dbType);
        if (!(line instanceof LineString) || line.getNumPoints() < 2)
            return calculateWidthFromDistance(gafPart, location);

        final LineString ls = (LineString) line;

        final LocationIndexedLine lineRef = new LocationIndexedLine(line);
        final LinearLocation loc = lineRef.project(location.getCoordinate());
        final Coordinate closestPt = loc.getCoordinate(line);

        final double distance = ls.getCoordinateN(0).distance(closestPt);
        return new BigDecimal(distance).setScale(3, BigDecimal.ROUND_HALF_UP);

    }
}