Example usage for java.math BigDecimal ROUND_HALF_EVEN

List of usage examples for java.math BigDecimal ROUND_HALF_EVEN

Introduction

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

Prototype

int ROUND_HALF_EVEN

To view the source code for java.math BigDecimal ROUND_HALF_EVEN.

Click Source Link

Document

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

Usage

From source file:org.mrgeo.data.shp.util.FileUtils.java

public static String getLength(long length) {
    if (length > (KB * KB * KB)) {
        BigDecimal bd = new BigDecimal(length / (KB * KB * KB));
        bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        return formatter.format(bd.doubleValue()) + "GB";
    } else if (length > (KB * KB)) {
        BigDecimal bd = new BigDecimal(length / (KB * KB));
        bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        return formatter.format(bd.doubleValue()) + "MB";
    } else if (length > (KB)) {
        BigDecimal bd = new BigDecimal(length / (KB));
        bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        return formatter.format(bd.doubleValue()) + "KB";
    } else {/*from  w  w  w .j  a v  a2 s . co m*/
        return formatter.format(length) + "B";
    }
}

From source file:org.libreplan.business.planner.entities.PlanningData.java

/**
 * Prevents division by zero// w  w w  . ja  v a 2  s  .  c o  m
 *
 * @param numerator
 * @param denominator
 * @return
 */
private BigDecimal divide(BigDecimal numerator, int denominator) {
    if (denominator == 0) {
        return BigDecimal.ZERO;
    }
    return numerator.divide(BigDecimal.valueOf(denominator), 8, BigDecimal.ROUND_HALF_EVEN);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.student.candidacy.registrations.RegisteredDegreeCandidaciesWithApplyForResidence.java

private BigDecimal getEntryGrade(final StudentCandidacy candidacy) {
    return new BigDecimal(candidacy.getEntryGrade().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_EVEN);
}

From source file:com.salesmanager.catalog.product.ProductDetailsAction.java

public String createReview() {

    try {/*from  w ww.ja va  2 s .  c  o m*/

        MerchantStore store = SessionUtil.getMerchantStore(super.getServletRequest());

        // requires Customer
        Customer customer = SessionUtil.getCustomer(super.getServletRequest());
        if (customer == null) {
            super.setMessage("message.review.loggedin");
            return INPUT;
        }

        // product details
        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
        product = cservice.getProduct(this.getProduct().getProductId());
        product.setLocale(super.getLocale());

        // create review

        // check text
        if (StringUtils.isBlank(this.getReviewText()) || StringUtils.isBlank(this.getReviewText())) {
            super.setErrorMessage("error.messag.review");
            return INPUT;
        }

        Review r = new Review();
        r.setCustomerId(customer.getCustomerId());
        r.setCustomerName(customer.getName());
        r.setDateAdded(new Date());
        r.setLastModified(new Date());
        r.setProductId(product.getProductId());
        r.setProductName(product.getName());
        r.setReviewRating(this.getRating());

        r.setLocale(super.getLocale());

        ReviewDescription description = new ReviewDescription();
        description.setReviewText(this.getReviewText());

        Set s = new HashSet();
        s.add(description);

        r.setDescriptions(s);

        cservice.addProductReview(store, r);

        counter = cservice.countAverageRatingPerProduct(this.getProduct().getProductId());

        if (counter != null) {

            double average = counter.getAverage();
            BigDecimal bdaverage = new BigDecimal(average);
            bdaverage.setScale(2, BigDecimal.ROUND_HALF_EVEN);
            product.setProductReviewCount(counter.getCount());
            product.setProductReviewAvg(bdaverage);
            cservice.saveOrUpdateProduct(product);
        }

        super.setMessage("message.review.created");

    } catch (Exception e) {
        logger.error(e);
        super.setTechnicalMessage();
        return INPUT;
    }

    return SUCCESS;

}

From source file:org.gnucash.android.ui.transaction.dialog.TransferFundsDialogFragment.java

@Nullable
@Override/*  ww  w  .  ja v a  2 s . c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_transfer_funds, container, false);
    ButterKnife.bind(this, view);

    TransactionsActivity.displayBalance(mStartAmountLabel, mOriginAmount);
    String fromCurrencyCode = mOriginAmount.getCommodity().getCurrencyCode();
    mFromCurrencyLabel.setText(fromCurrencyCode);
    mToCurrencyLabel.setText(mTargetCurrencyCode);
    mConvertedAmountCurrencyLabel.setText(mTargetCurrencyCode);

    mSampleExchangeRate.setText(
            String.format(getString(R.string.sample_exchange_rate), fromCurrencyCode, mTargetCurrencyCode));
    final InputLayoutErrorClearer textChangeListener = new InputLayoutErrorClearer();

    CommoditiesDbAdapter commoditiesDbAdapter = CommoditiesDbAdapter.getInstance();
    String commodityUID = commoditiesDbAdapter.getCommodityUID(fromCurrencyCode);
    Commodity currencyCommodity = commoditiesDbAdapter.getCommodity(mTargetCurrencyCode);
    String currencyUID = currencyCommodity.getUID();
    PricesDbAdapter pricesDbAdapter = PricesDbAdapter.getInstance();
    Pair<Long, Long> pricePair = pricesDbAdapter.getPrice(commodityUID, currencyUID);

    if (pricePair.first > 0 && pricePair.second > 0) {
        // a valid price exists
        Price price = new Price(commodityUID, currencyUID);
        price.setValueNum(pricePair.first);
        price.setValueDenom(pricePair.second);
        mExchangeRateInput.setText(price.toString());

        BigDecimal numerator = new BigDecimal(pricePair.first);
        BigDecimal denominator = new BigDecimal(pricePair.second);
        // convertedAmount = mOriginAmount * numerator / denominator
        BigDecimal convertedAmount = mOriginAmount.asBigDecimal().multiply(numerator).divide(denominator,
                currencyCommodity.getSmallestFractionDigits(), BigDecimal.ROUND_HALF_EVEN);
        DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance();
        mConvertedAmountInput.setText(formatter.format(convertedAmount));
    }

    mExchangeRateInput.addTextChangedListener(textChangeListener);
    mConvertedAmountInput.addTextChangedListener(textChangeListener);

    mConvertedAmountRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mConvertedAmountInput.setEnabled(isChecked);
            mConvertedAmountInputLayout.setErrorEnabled(isChecked);
            mExchangeRateRadioButton.setChecked(!isChecked);
            if (isChecked) {
                mConvertedAmountInput.requestFocus();
            }
        }
    });

    mExchangeRateRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mExchangeRateInput.setEnabled(isChecked);
            mExchangeRateInputLayout.setErrorEnabled(isChecked);
            mFetchExchangeRateButton.setEnabled(isChecked);
            mConvertedAmountRadioButton.setChecked(!isChecked);
            if (isChecked) {
                mExchangeRateInput.requestFocus();
            }
        }
    });

    mFetchExchangeRateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: Pull the exchange rate for the currency here
        }
    });

    mCancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    mSaveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            transferFunds();
        }
    });
    return view;
}

From source file:org.egov.stms.report.service.SewerageBaseRegisterReportService.java

private void setDemandDetails(final SewerageIndex sewerageIndex,
        final SewerageBaseRegisterResult searchResult) {
    searchResult.setArrears(sewerageIndex.getArrearAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getArrearAmount().setScale(0, BigDecimal.ROUND_HALF_EVEN));
    searchResult.setCurrentDemand(sewerageIndex.getDemandAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getDemandAmount().setScale(0, BigDecimal.ROUND_HALF_EVEN));
    searchResult.setAdvanceAmount(sewerageIndex.getExtraAdvanceAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getExtraAdvanceAmount().setScale(0, BigDecimal.ROUND_HALF_EVEN));
    searchResult.setArrearsCollected(sewerageIndex.getCollectedArrearAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getCollectedArrearAmount().setScale(0, BigDecimal.ROUND_HALF_EVEN));
    searchResult.setCurrentTaxCollected(
            getCollectedDemandAmount(sewerageIndex).setScale(0, BigDecimal.ROUND_HALF_EVEN));
    searchResult.setTotalTaxCollected(sewerageIndex.getCollectedArrearAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getCollectedArrearAmount().add(getCollectedDemandAmount(sewerageIndex)).setScale(0,
                    BigDecimal.ROUND_HALF_EVEN));
    searchResult.setTotalDemand(sewerageIndex.getTotalAmount() == null ? BigDecimal.ZERO
            : sewerageIndex.getTotalAmount().setScale(0, BigDecimal.ROUND_HALF_EVEN));
}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Format./*from www .  j av  a 2  s .c  o  m*/
 *
 * @param doubData
 *            the doub data
 * @param precision
 *            the precision
 * @param scale
 *            the scale
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String format(double doubData, int precision, int scale) throws Exception {
    BigDecimal decData = new BigDecimal(doubData);
    decData = decData.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
    String strData = decData.toString();

    // prepare the final string
    int finalLen = precision + 1;
    String finalStr;
    if (finalLen <= strData.length()) {
        finalStr = strData.substring(0, finalLen);
    } else {
        finalStr = "";
        for (int i = 0; i < finalLen - strData.length(); i++) {
            finalStr = finalStr + " ";
        }
        finalStr = finalStr + strData;
    }

    return (finalStr);
}

From source file:Main.java

/**
 * Compute the natural logarithm of x to a given scale, x > 0.
 * Use Newton's algorithm./* ww w .  j a v  a 2s.  c om*/
 */
private static BigDecimal lnNewton(BigDecimal x, int scale) {
    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal term;

    // Convergence tolerance = 5*(10^-(scale+1))
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);

    // Loop until the approximations converge
    // (two successive approximations are within the tolerance).
    do {

        // e^x
        BigDecimal eToX = exp(x, sp1);

        // (e^x - n)/e^x
        term = eToX.subtract(n).divide(eToX, sp1, BigDecimal.ROUND_DOWN);

        // x - (e^x - n)/e^x
        x = x.subtract(term);

        Thread.yield();
    } while (term.compareTo(tolerance) > 0);

    return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Format./*from  ww  w . j a  v a  2s .c  o m*/
 *
 * @param decData
 *            the dec data
 * @param precision
 *            the precision
 * @param scale
 *            the scale
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String format(BigDecimal decData, int precision, int scale) throws Exception {
    decData = decData.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
    String strData = decData.toString();

    // prepare the final string
    int finalLen = precision + 1;
    String finalStr;
    if (finalLen <= strData.length()) {
        finalStr = strData.substring(0, finalLen);
    } else {
        finalStr = "";
        for (int i = 0; i < finalLen - strData.length(); i++) {
            finalStr = finalStr + " ";
        }
        finalStr = finalStr + strData;
    }

    return (finalStr);
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static BigDecimal safeBigDecimal(final String number, final int newScale) {
    BigDecimal result = null;/* w  w  w. ja  va  2 s . c om*/
    if (StringUtils.isNotEmpty(number)) {
        result = new BigDecimal(number, MathContext.DECIMAL64).setScale(newScale, BigDecimal.ROUND_HALF_EVEN);
    }
    return result;
}