Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:ccc.cli.StringToDecConverterUtil.java

/**
 *
 * Converts a number represented as text to a decimal number.
 *
 * @param textNumber text representation of a number
 * @return BigDecimal//from  w w w.j  av  a2s.  c  o m
 */
public BigDecimal convert(final String textNumber) {
    BigDecimal decNumber = null;
    if (textNumber != null && textNumber.matches(DECIMAL_PATTERN)) {
        // BigNumber(String) constructor does not allow commas
        decNumber = new BigDecimal(textNumber.replaceAll(",", ""));

        if (decNumber.precision() > MAX_PRECISION
                || decNumber.scale() < 0
                        && Math.abs(decNumber.scale()) + decNumber.precision() > MAX_PRECISION - MAX_SCALE
                || decNumber.compareTo(MAX_VALUE) == 1) {

            LOG.warn("Value is larger than maximum precision allowed " + "and was rejected.");
            return null;
        }

        if (decNumber.scale() > MAX_SCALE) {
            LOG.trace("Scale is bigger than maximum allowed: " + decNumber.scale() + ". Resetting scale.");
            decNumber = decNumber.setScale(MAX_SCALE, RoundingMode.DOWN);
        }
    }
    return decNumber;
}

From source file:org.kuali.kpme.tklm.time.timeblock.TimeBlockBo.java

public void setHours(BigDecimal hours) {
    if (hours != null) {
        this.hours = hours.setScale(HrConstants.BIG_DECIMAL_SCALE, HrConstants.BIG_DECIMAL_SCALE_ROUNDING);
    } else {//from  w w  w .  ja  va 2 s .c om
        this.hours = hours;
    }
}

From source file:org.kuali.kpme.tklm.time.timeblock.TimeBlockBo.java

public void setAmount(BigDecimal amount) {
    if (amount != null) {
        this.amount = amount.setScale(HrConstants.BIG_DECIMAL_SCALE, HrConstants.BIG_DECIMAL_SCALE_ROUNDING);
    } else {/*from  w  w w  .  j  ava2s .c o m*/
        this.amount = amount;
    }
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addInvestor(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) {
    double investAmount = 0;
    long tradeId = trade.getId();
    long detailId = detail.getId();
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount());
    investAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    investAmount = Math.floor(investAmount);
    // /*  ww w .  j a  va2 s  . c  o m*/
    if (investAmount > 0)
        tradeDetailDao.addTradeDetail(new TradeDetail(detail.getUserId(), tradeId, (long) investAmount, 12,
                divsionRuleRole.getPhase(), String.valueOf(detailId)));
}

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

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

        @Override//from www .  j  a  va  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:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addInvestorByMonthInterest(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) {
    int monthes = trade.getTimeLimit();

    double investAmount = 0;
    long tradeId = trade.getId();
    long detailId = detail.getId();
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount());
    investAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    double monthMoney = investAmount / monthes;
    // investAmount = Math.floor(investAmount);
    monthMoney = Math.floor(monthMoney);

    for (int i = 0; i < monthes; i++) {
        TradeDetail tradeDetail = new TradeDetail(detail.getUserId(), tradeId, (long) monthMoney, 12,
                divsionRuleRole.getPhase(), String.valueOf(detailId));
        tradeDetail.setRepayPeriodNo(i + 1);
        tradeDetail.setRepayPeriodCount(monthes);
        tradeDetailDao.addTradeDetail(tradeDetail);
    }// w  w w  .  ja v  a  2 s.  co  m
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addPlatform(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) {
    double platformAmount = 0;
    long tradeId = trade.getId();
    long detailId = detail.getId();
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * trade.getLoanedAmount());
    platformAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    platformAmount = Math.floor(platformAmount);
    // // w  w w .j a  v  a 2 s  . com
    if (platformAmount > 0) {
        UserBaseInfoDO profitUser = userBaseInfoManager
                .queryByAccountId(AppConstantsUtil.getProfitSharingAccount());
        tradeDetailDao.addTradeDetail(new TradeDetail(profitUser.getUserId(), tradeId, (long) platformAmount, 7,
                divsionRuleRole.getPhase(), String.valueOf(detailId)));
    }
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional(readOnly = true)/*www . jav  a 2  s .  c om*/
public List<Map<String, Object>> getShop(String shopName, String shopTypeNo, String memberNo) throws Exception {
    String sql = "select " + " tsi.shop_no shopNo, " + " tsi.shop_name shopName, " + " tsi.shop_logo shopLogo, "
            + " tsi.shop_summary shopSummary, " + " tsi.is_recommend isRecommend, "
            + " tcc.serviceGrade serviceGrade, " + " tcc.deliveryGrade deliveryGrade, "
            + " if(tcs.shop_no is null,'0','1') isCollect " + " from tbl_shop_info tsi left join   "
            + " (select avg(tcc.service_grade) serviceGrade,avg(tcc.delivery_grade) deliveryGrade , "
            + " tcc.shop_no from tbl_commodity_comment tcc group by(tcc.shop_no) ) tcc on tsi.shop_no = tcc.shop_no "
            + " left join (select * from tbl_shop_collect tcs where tcs.member_no = :memberNo) tcs on tsi.shop_no = tcs.shop_no "
            + "where tsi.status=2 ";
    if (shopTypeNo != null && !shopTypeNo.equals("")) {
        sql = sql + "and tsi.shop_type_no=:shopTypeNo ";
    }
    if (shopName != null && !shopName.equals("")) {
        sql = sql + "and tsi.shop_name like :shopName ";
    }
    Query query = shopDao.createSQLQuery(sql);
    if (shopTypeNo != null && !shopTypeNo.equals("")) {
        query.setParameter("shopTypeNo", shopTypeNo);
    }
    if (shopName != null && !shopName.equals("")) {
        query.setParameter("shopName", "%" + shopName + "%");
    }
    query.setParameter("memberNo", memberNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> results = query.list();
    if (results != null && !results.isEmpty()) {
        for (Map<String, Object> result : results) {
            Double servGrade = result.get("serviceGrade") == null ? 0
                    : Double.valueOf(result.get("serviceGrade").toString());
            BigDecimal serviceGrade = new BigDecimal(servGrade);
            serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            result.put("serviceGrade", serviceGrade.doubleValue());
            Double delGrade = result.get("deliveryGrade") == null ? 0
                    : Double.valueOf(result.get("deliveryGrade").toString());
            BigDecimal deliveryGrade = new BigDecimal(delGrade);
            deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            result.put("deliveryGrade", deliveryGrade.doubleValue());
        }
    }
    return results;
}

From source file:mx.edu.um.mateo.inventario.web.SalidaController.java

@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
    log.debug("Mostrando salida {}", id);
    Salida salida = salidaDao.obtiene(id);
    switch (salida.getEstatus().getNombre()) {
    case Constantes.ABIERTA:
        modelo.addAttribute("puedeEditar", true);
        modelo.addAttribute("puedeEliminar", true);
        modelo.addAttribute("puedeCerrar", true);
        break;//from  w  w  w  .j  a  v  a  2  s  .c  o  m
    case Constantes.CERRADA:
        modelo.addAttribute("puedeCancelar", true);
        modelo.addAttribute("puedeReporte", true);
        break;
    case Constantes.CANCELADA:
        log.debug("Puede ver reporte");
        modelo.addAttribute("puedeReporte", true);
        break;
    }

    modelo.addAttribute("salida", salida);

    BigDecimal subtotal = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    BigDecimal iva = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    for (LoteSalida lote : salida.getLotes()) {
        subtotal = subtotal.add(lote.getPrecioUnitario().multiply(lote.getCantidad()));
        iva = iva.add(lote.getIva());
    }
    BigDecimal total = subtotal.add(iva);
    modelo.addAttribute("subtotal", subtotal.setScale(2, RoundingMode.HALF_UP));
    modelo.addAttribute("iva", iva);
    modelo.addAttribute("total", total.setScale(2, RoundingMode.HALF_UP));
    if (iva.compareTo(salida.getIva()) == 0 && total.compareTo(salida.getTotal()) == 0) {
        modelo.addAttribute("estiloTotales", "label label-success");
    } else {
        BigDecimal variacion = new BigDecimal("0.05");
        BigDecimal topeIva = salida.getIva().multiply(variacion);
        BigDecimal topeTotal = salida.getTotal().multiply(variacion);
        log.debug("Estilos {} {} {} {} {} {}",
                new Object[] { iva, salida.getIva(), topeIva, total, salida.getTotal(), topeTotal });
        if (iva.compareTo(salida.getIva()) < 0 || total.compareTo(salida.getTotal()) < 0) {
            log.debug("La diferencia es menor");
            if (iva.compareTo(salida.getIva().subtract(topeIva)) >= 0
                    && total.compareTo(salida.getTotal().subtract(topeTotal)) >= 0) {
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        } else {
            log.debug("La diferencia es mayor {} {}",
                    new Object[] { iva.compareTo(salida.getIva().add(topeIva)),
                            total.compareTo(salida.getTotal().add(topeTotal)) });
            if (iva.compareTo(salida.getIva().add(topeIva)) <= 0
                    && total.compareTo(salida.getTotal().add(topeTotal)) <= 0) {
                log.debug("estilo warning");
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                log.debug("estilo error");
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        }
    }

    return "inventario/salida/ver";
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addBrokerRelationUser(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole)
        throws Exception {
    long detailId = detail.getId();
    long tradeId = trade.getId();
    Page<UserRelationDO> userRelationsPage = userRelationManager.getRelationsByConditions(null, null,
            detail.getUserId(), null);//from w w w  .  j  av a  2  s  .  c  o m

    UserBaseInfoDO jjrUserBaseInfo = null;
    if (ListUtil.isNotEmpty(userRelationsPage.getResult())) {
        UserRelationDO relationDO = userRelationsPage.getResult().get(0);
        List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager.queryByType(null,
                String.valueOf(relationDO.getParentId()));
        if (ListUtil.isNotEmpty(curParentJjrs)) {
            if (UserTypeEnum.GR.code().equals(curParentJjrs.get(0).getType())) {
                jjrUserBaseInfo = curParentJjrs.get(0);
            }
        }
        if (jjrUserBaseInfo == null && this.sysFunctionConfigService.isAllEconomicMan()) {
            jjrUserBaseInfo = userBaseInfoManager.queryByUserId(detail.getUserId());
        }
    }
    if (jjrUserBaseInfo != null) {
        ProfitAsignInfo profitAsignInfo = userRelationManager
                .queryByReceiveIdAndDistributionId(detail.getUserId(), jjrUserBaseInfo.getUserId());
        double distributionRule = 0;
        double distributionAmount = 0;
        if (profitAsignInfo != null) {
            distributionRule = CommonUtil.mul(divsionRuleRole.getRule(),
                    profitAsignInfo.getDistributionQuota());
        }
        double actualRule = divsionRuleRole.getRule() - distributionRule;
        BigDecimal bg = new BigDecimal(getDaysRuleRate(actualRule, trade) * detail.getAmount());
        double jjrAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
        jjrAmount = Math.floor(jjrAmount);
        if (distributionRule > 0) {
            BigDecimal bgdis = new BigDecimal(getDaysRuleRate(distributionRule, trade) * detail.getAmount());
            distributionAmount = bgdis.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
            distributionAmount = Math.floor(distributionAmount);
            //???
            TradeDetail extraDetail = new TradeDetail(detail.getUserId(), tradeId, (long) distributionAmount,
                    12, divsionRuleRole.getPhase(), String.valueOf(detailId));
            extraDetail.setProfitType(1);
            extraDetail.setProfitRate(distributionRule);
            tradeDetailDao.addTradeDetail(extraDetail);
        }

        //?
        tradeDetailDao.addTradeDetail(new TradeDetail(jjrUserBaseInfo.getUserId(), tradeId, (long) jjrAmount,
                11, divsionRuleRole.getPhase(), String.valueOf(detailId)));
    }

}