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:churashima.action.manage.ExpensesAction.java

@Execute(input = "expenses.jsp")
public String entryExecute() {

    ExpensesDao expensesDao = SingletonS2Container.getComponent(ExpensesDao.class);
    SubjectDao subjectDao = SingletonS2Container.getComponent(SubjectDao.class);

    Expenses expenses = new Expenses();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    try {/*from   w  w w  . j  a v  a 2  s .c  om*/
        expenses.date = sdf.parse(expensesForm.strDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (expensesForm.subjectId == null) {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", //??????
                new Object[] { "" }));
        ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);

        expensesForm.subjectList = subjectDao.selectForSearch(null, null);

        return "expenses.jsp";
    }

    expenses.subjectId = expensesForm.subjectId;
    expenses.place = expensesForm.place;
    expenses.name = expensesForm.name;
    expenses.comment = expensesForm.comment;
    expenses.category = expensesForm.category;
    expenses.categoryDetail = expensesForm.detail;
    expenses.openFlg = expensesForm.openFlg;
    expenses.isExcludeTax = expensesForm.isExcludeTax;

    TaxDao taxDao = SingletonS2Container.getComponent(TaxDao.class);
    BigDecimal tax = taxDao.selectByDate(expenses.date);

    if (Const.TAX_EXCLUDE.equals(expensesForm.isExcludeTax)) {
        // ?????
        expenses.priceTax = expensesForm.price.multiply(tax);
        expenses.priceExcludeTax = expensesForm.price;
        expenses.price = expenses.priceExcludeTax.add(expenses.priceTax);

    } else {
        // ????
        expenses.price = expensesForm.price;
        expenses.priceExcludeTax = expensesForm.price.divide(BigDecimal.valueOf(1).add(tax), 3,
                BigDecimal.ROUND_HALF_UP); // ?
        expenses.priceTax = expenses.price.subtract(expenses.priceExcludeTax);
    }

    // 
    Timestamp now = new Timestamp(System.currentTimeMillis());
    expenses.deleted = false;
    expenses.updDate = now;
    expenses.updId = null;
    expenses.insDate = now;
    expenses.insId = null;

    try {
        expensesDao.insert(expenses);
    } catch (SQLRuntimeException e) {
        SQLException e2 = (SQLException) e.getCause();
        if (e2.getErrorCode() == 0) {

            //???
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.already.entried", //??????
                    new Object[] { "????" }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);

            return "/manage/expenses";
        }
    }
    return "/manage/expenses";
}

From source file:ch.algotrader.service.TransactionPersistenceServiceImpl.java

/**
 * {@inheritDoc}/*from ww w .  j av a  2  s .c  o  m*/
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public String resetCashBalances() {

    // get all existing cashBalances
    Collection<CashBalance> existingCashBalances = this.cashBalanceDao.loadAll();

    // sum all transactions
    Collection<Transaction> transactions = this.transactionDao.loadAll();
    BigDecimalMap<Pair<Strategy, Currency>> map = new BigDecimalMap<>();
    for (Transaction transaction : transactions) {

        transaction.initializeSecurity(HibernateInitializer.INSTANCE);

        // process all currenyAmounts
        for (CurrencyAmountVO currencyAmount : transaction.getAttributions()) {
            map.increment(new Pair<>(transaction.getStrategy(), currencyAmount.getCurrency()),
                    currencyAmount.getAmount());
        }
    }

    // create cash balances
    StringBuilder buffer = new StringBuilder();
    for (Map.Entry<Pair<Strategy, Currency>, BigDecimal> entry : map.entrySet()) {

        Strategy strategy = entry.getKey().getFirst();
        Currency currency = entry.getKey().getSecond();
        BigDecimal amount = entry.getValue().setScale(this.commonConfig.getPortfolioDigits(),
                BigDecimal.ROUND_HALF_UP);

        CashBalance cashBalance = this.cashBalanceDao.findByStrategyAndCurrency(strategy, currency);
        if (cashBalance != null) {

            existingCashBalances.remove(cashBalance);

            BigDecimal oldAmount = cashBalance.getAmount();
            if (oldAmount.doubleValue() != amount.doubleValue()) {

                cashBalance.setAmount(amount);

                String info = "adjusted cashBalance " + cashBalance + " from " + oldAmount;
                LOGGER.info(info);
                buffer.append(info + "\n");

            }

        } else {

            cashBalance = CashBalance.Factory.newInstance();
            cashBalance.setCurrency(currency);
            cashBalance.setAmount(amount);
            cashBalance.setStrategy(strategy);

            this.cashBalanceDao.save(cashBalance);

            String info = "created cashBalance " + cashBalance;
            LOGGER.info(info);
            buffer.append(info + "\n");

        }
    }

    // remove all obsolete cashBalances
    for (CashBalance cashBalance : existingCashBalances) {

        Strategy strategy = cashBalance.getStrategy();

        String info = "removed cashBalance " + cashBalance;
        LOGGER.info(info);
        buffer.append(info + "\n");
    }

    this.cashBalanceDao.deleteAll(existingCashBalances);

    return buffer.toString();

}

From source file:org.egov.infra.gis.service.GeoLocationService.java

/**
 * //from   w  w w .j a va 2  s.  c o  m
 * @param wardWiseData Map<String, Integer>- Map having the key as the ward number and value as the no of complaints/properties/assets
 *    in that ward. e.g [<Ward Number>,<no Of Complaints/assets/properties> ]
 * 
 * @param colorCodes Map<Integer,String> - Map having colour codes , the key as the the colour priority and value as the colour 
 * code in RGB format. e.g - key = 1 , means the associated colour to represent the ward having  no of complaints/assets/properties
 * that falls in highest range , key = 2 means associated colour to represent ward having  no of complaints/assets/properties
 * that falls in the 2nd highest range and so on.
 * example :  (1, "FF0000");
 *           (2, "8968CD");
 *            (3, "FFA500");
 *            (4, "4169E1");
 *            (5, "008B00");
 */

public static void setKmlDataToCacheAndRequest(Map<String, BigDecimal> wardWiseData,
        Map<Integer, String> colorCodes, String kmlPath, HttpServletRequest request) {

    LOGGER.debug("GeoLocationService | setKmlDataToCacheAndRequest | Start");

    int totalNoOfColors = colorCodes.size();
    BigDecimal wardDataMinAmount = Collections.min(wardWiseData.values()).setScale(0, BigDecimal.ROUND_HALF_UP); // to hold the minimum amount in all the wards.
    BigDecimal wardDataMaxAmount = Collections.max(wardWiseData.values()).setScale(0, BigDecimal.ROUND_HALF_UP); // to hold the maximum amount in all the wards.
    if ((wardDataMaxAmount.subtract(wardDataMinAmount)).compareTo(BigDecimal.valueOf(totalNoOfColors)) == -1) {
        throw new ValidationException(Arrays.asList(new ValidationError("colorrange",
                "no of colors supplied is more than the range of data " + "in the wards")));
    }

    BigDecimal rangeSize = getRangeSize(wardDataMinAmount, wardDataMaxAmount, totalNoOfColors);

    GeoKmlInfo geoKmlInfo = new GeoKmlInfo();
    Map<String, String> wardWiseKmlColorStyle = new HashMap<String, String>();

    for (Map.Entry<String, BigDecimal> entry : wardWiseData.entrySet()) {
        wardWiseKmlColorStyle.put("style" + entry.getKey(),
                getStyleColorName(entry.getValue(), wardDataMinAmount, totalNoOfColors, rangeSize));
    }

    geoKmlInfo.setWardWiseColor(wardWiseKmlColorStyle);
    geoKmlInfo.setColorCodes(convertToKmlColor(colorCodes));

    request.setAttribute(GeoLocationConstants.KML_DATA_MODEL_JBOSS_CACHE_KEY_NAME,
            putKmlDataToCache(geoKmlInfo));
    request.setAttribute(GeoLocationConstants.COLOR_CODE_AND_RANGE_MAP_NAME,
            getColorRange(wardDataMinAmount, wardDataMaxAmount, rangeSize, colorCodes));
    if (null != kmlPath && StringUtils.isNotEmpty(kmlPath)) {
        request.setAttribute(GeoLocationConstants.KML_URL_PATH_REQ_ATTR_NAME, kmlPath);
    }

    LOGGER.debug("GeoLocationService | setKmlDataToCacheAndRequest | End");

}

From source file:hydrograph.ui.dataviewer.filemanager.DataViewerFileManager.java

/**
 * //from   w w  w .ja v  a  2 s.  c  om
 * Download debug file in data viewer workspace
 * @param filterApplied 
 * @param filterConditions 
 * 
 * @return error code
 */
public StatusMessage downloadDataViewerFiles(boolean filterApplied, FilterConditions filterConditions,
        boolean isOverWritten) {

    // Get csv debug file name and location 
    String csvDebugFileAbsolutePath = null;
    String csvDebugFileName = null;
    try {
        if (filterConditions != null) {
            if (!filterConditions.getRetainRemote()) {
                if (!filterApplied) {
                    csvDebugFileAbsolutePath = getDebugFileAbsolutePath();
                } else {
                    csvDebugFileAbsolutePath = getDebugFileAbsolutePath();
                    csvDebugFileName = getFileName(csvDebugFileAbsolutePath);
                    csvDebugFileAbsolutePath = getFilterFileAbsolutePath(filterConditions, csvDebugFileName);
                }
            } else {
                csvDebugFileAbsolutePath = getDebugFileAbsolutePath();
                csvDebugFileName = getFileName(csvDebugFileAbsolutePath);
                csvDebugFileAbsolutePath = getFilterFileAbsolutePath(filterConditions, csvDebugFileName);
            }
        } else {
            csvDebugFileAbsolutePath = getDebugFileAbsolutePath();
        }
    } catch (MalformedURLException malformedURLException) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, malformedURLException.getMessage(),
                malformedURLException);
        StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR,
                Messages.UNABLE_TO_FETCH_DEBUG_FILE
                        + ": either no legal protocol could be found in a specification string or the path could not be parsed.")
                                .errorStatus(status).build();
        logger.error("Unable to fetch viewData file", malformedURLException);
        return statusMessage;
    } catch (HttpException httpException) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, httpException.getMessage(),
                httpException);
        StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR,
                Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": error from Http client").errorStatus(status).build();
        logger.error("Unable to fetch viewData file", httpException);
        return statusMessage;
    } catch (NumberFormatException numberFormateException) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, numberFormateException.getMessage(),
                numberFormateException);
        StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR,
                Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": please check if port number is defined correctly")
                        .errorStatus(status).build();
        logger.error("Unable to fetch viewData file", numberFormateException);
        return statusMessage;
    } catch (IOException ioException) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ioException.getMessage(), ioException);
        StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR,
                Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": please check if service is running")
                        .errorStatus(status).build();
        logger.error("Unable to fetch viewData file", ioException);
        return statusMessage;
    }
    if (csvDebugFileAbsolutePath != null) {
        csvDebugFileName = csvDebugFileAbsolutePath
                .substring(csvDebugFileAbsolutePath.lastIndexOf("/") + 1, csvDebugFileAbsolutePath.length())
                .replace(DEBUG_DATA_FILE_EXTENTION, "").trim();
    }

    //Copy csv debug file to Data viewers temporary file location
    if (StringUtils.isNotBlank(csvDebugFileName)) {
        String dataViewerDebugFile = getDataViewerDebugFile(csvDebugFileName);

        try {
            if (!filterApplied) {
                copyCSVDebugFileToDataViewerStagingArea(jobDetails, csvDebugFileAbsolutePath,
                        dataViewerDebugFile, isOverWritten);
            } else {
                copyFilteredFileToDataViewerStagingArea(jobDetails, csvDebugFileAbsolutePath,
                        dataViewerDebugFile);
            }
        } catch (IOException | JSchException e1) {
            logger.error("Unable to fetch viewData file", e1);
            return new StatusMessage(StatusConstants.ERROR,
                    Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": unable to copy the files from temporary location");
        }

        File debugFile = new File(dataViewerDebugFile);
        double debugFileSizeInByte = (double) debugFile.length();
        double debugFileSizeKB = (debugFileSizeInByte / 1024);
        debugFileSizeInKB = new BigDecimal(debugFileSizeKB).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        // Delete csv debug file after copy
        deleteFileOnRemote(jobDetails, csvDebugFileName);

        // Check for empty csv debug file
        if (isEmptyDebugCSVFile(dataViewerFilePath, dataViewerFileName)) {
            logger.error("Empty viewData file");
            return new StatusMessage(StatusConstants.ERROR, Messages.EMPTY_DEBUG_FILE);
        }
    }
    return new StatusMessage(StatusConstants.SUCCESS);
}

From source file:com.visionet.platform.cooperation.service.OrderService.java

/**
 * ?  ?/*  w  ww.j  a  v  a 2s .  c  o m*/
 *
 * @param orderNo
 * @param partnerOrderNo
 * @param evaluateScore
 * @param describe
 */
public void evaluateDriver(String orderNo, String partnerOrderNo, Integer evaluateScore, String describe) {
    if (StringUtils.isBlank(orderNo)) {
        throw new BizException("???");
    }
    Order order = orderMapper.selectByPrimaryKey(orderNo);
    if (order == null) {
        throw new BizException("??");
    }
    if (order.getStatus() == null || order.getStatus() != 2) {
        throw new BizException("???");
    }
    Integer evaluateScore2 = order.getCarUserGrade();
    if (evaluateScore2 != null) {
        throw new BizException("????");
    }
    Customer customer = customerMapper.selectByPrimaryKey(order.getCustomerPhone());
    if (customer == null) {
        throw new BizException("??");
    }
    order.setCarUserGrade(evaluateScore);
    order.setBakstr4(describe);
    orderMapper.updateByPrimaryKeySelective(order);

    CarUser carUser = carUserMapper.selectByPrimaryKey(order.getCarId());
    if (carUser == null) {
        throw new BizException("??");
    }
    String starStr = carUser.getBakstr2();
    Integer allStar = 0;
    if (StringUtils.isBlank(starStr)) {
        allStar = 0;
    } else {
        allStar = Integer.parseInt(starStr);
    }
    Integer orderNum = carUser.getOrderCount();
    if (orderNum == 0) {
        throw new BizException("???");
    }
    Integer star = allStar + evaluateScore;
    Double d = (double) star;
    Double avgstar = d / orderNum;
    double value = new BigDecimal(avgstar).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    if (value > 5) {
        value = 5;
    }
    carUser.setBakstr2(star.toString());
    carUser.setGrade(value);
    carUserMapper.updateByPrimaryKey(carUser);
}

From source file:com.chiorichan.util.ObjectUtil.java

public static Long castToLongWithException(Object value) {
    if (value == null)
        return null;

    switch (value.getClass().getName()) {
    case "java.lang.Long":
        return (Long) value;
    case "java.lang.String":
        return Long.parseLong((String) value);
    case "java.lang.Integer":
        return (Long) value;
    case "java.lang.Double":
        return (Long) value;
    case "java.lang.Boolean":
        return ((boolean) value) ? 1L : 0L;
    case "java.math.BigDecimal":
        return ((BigDecimal) value).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
    default:/*from   w w w .  j  a  va2s.co  m*/
        throw new ClassCastException("Uncaught Convertion to Long of Type: " + value.getClass().getName());
    }
}

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

/**
 * @param demandDetailSet//from w  w  w  .java2 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:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * /*from www . j a  va 2 s.c o m*/
 * @return
 */
public double getBalance() throws Exception {
    if (!enableAccounting) {
        return 0.0;
    }

    if (balance == null) {
        Object identity = null;
        try {
            identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);
            log.debug("Getting entity manager ......");
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            Account account = (Account) em.find(Account.class, organizationId);
            balance = account.getCreditBalance();
        } finally {
            log.debug("Closing entity manager .....");
            MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
        }

    }
    if (balance != null) {
        return balance.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    } else {
        return 0.0;
    }

}

From source file:com.app.jdy.ui.CashAdvanceActivity.java

private void addEvents() {
    button.setOnClickListener(new OnClickListener() {

        @Override/*from w  w w  .jav  a  2 s .  c o m*/
        public void onClick(View v) {

            // ????
            if (HttpUtils.isNetworkConnected(CashAdvanceActivity.this)) {

                if (editText.getText().toString().length() == 0) {
                    Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT).show();
                } else {

                    // ?
                    int count = 0, start = 0;
                    while ((start = editText.getText().toString().indexOf(".", start)) >= 0) {
                        start += ".".length();
                        count++;
                    }
                    if (count > 1 || editText.getText().toString().indexOf(".") == 0) {
                        Toast.makeText(CashAdvanceActivity.this, "", Toast.LENGTH_SHORT)
                                .show();
                    } else {

                        // ?????
                        BigDecimal judgemoney = null;
                        try {
                            judgemoney = new BigDecimal(editText.getText().toString());
                        } catch (NumberFormatException e) {
                            Toast.makeText(CashAdvanceActivity.this, "",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        judgemoney = judgemoney.setScale(2, BigDecimal.ROUND_HALF_UP);

                        // ?????
                        String judgecanWithdCash = textView2.getText().toString();

                        if (textView4.getText().toString().equals("?")
                                || textView4.getText().toString().length() == 0
                                || textView3.getText().toString().length() == 0) {
                            Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (judgemoney.toString() == "0.00") {
                            Toast.makeText(CashAdvanceActivity.this, "?0?",
                                    Toast.LENGTH_SHORT).show();
                        } else if (judgemoney
                                .compareTo(BigDecimal.valueOf(Double.valueOf(judgecanWithdCash))) == 1) {
                            // BigDecimalcompareTo-1 ? 0
                            // 1
                            Toast.makeText(CashAdvanceActivity.this, "??????",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            editText.setText(judgemoney.toString());

                            withdrawCashDialog = new WithdrawCashDialog(CashAdvanceActivity.this,
                                    R.style.ForwardDialog, judgemoney.toString());
                            withdrawCashDialog.show();
                        }

                    }

                }
            } else {
                // ??
                Toast.makeText(CashAdvanceActivity.this, Constants.NO_INTENT_TIPS, Toast.LENGTH_LONG).show();
            }

        }
    });

    // ??????
    findViewById(R.id.cash_textView5).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(CashAdvanceActivity.this, BankCardActivity.class);

            Bundle bundle = new Bundle();
            bundle.putBoolean("isOk", true);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        }
    });

}

From source file:org.kuali.kfs.module.bc.businessobject.CalculatedSalaryFoundationTracker.java

/**
 * Gets the csfTimePercent attribute. Returns 2 decimal places, reguardless.
 *
 * @return Returns the csfTimePercent//from w  ww  .  j a va 2  s .c o m
 */
public BigDecimal getCsfTimePercent() {

    BigDecimal bigDecValue = this.csfTimePercent;
    bigDecValue = bigDecValue.setScale(PERCENTAGE_SCALE, BigDecimal.ROUND_HALF_UP);
    return bigDecValue;
}