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:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private void setSubcontracts(AwardSpecialItems awardSpecialItem) {
    List<AwardApprovedSubaward> awardApprovedSubawards = award.getAwardApprovedSubawards();
    for (AwardApprovedSubaward awardApprovedSubcontractBean : awardApprovedSubawards) {
        Subcontract subcontractType = awardSpecialItem.addNewSubcontract();
        BigDecimal bdecAmount = awardApprovedSubcontractBean.getAmount().bigDecimalValue();
        subcontractType.setAmount(bdecAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN));
        subcontractType.setAwardNumber(awardApprovedSubcontractBean.getAwardNumber());
        subcontractType.setSequenceNumber(awardApprovedSubcontractBean.getSequenceNumber());
        subcontractType.setSubcontractorName(awardApprovedSubcontractBean.getOrganizationName());
    }//from   w  ww  .  j  a  v  a 2s  . c  o  m
}

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

@Transactional(rollbackFor = Exception.class, value = "transactionManager")
@Override/*w  w  w .  j a va2s  . co m*/
public void createRelativeTrades(Trade trade) throws Exception {

    trade = tradeDao.getByTradeIdWithRowLock(trade.getId());
    // ?
    modifyStatus(trade.getId(), YrdConstants.TradeStatus.GUARANTEE_AUDITING);
    // ???
    tradeDao.updateIsNotifiedLoaner(trade.getId(), YrdConstants.MessageNotifyConstants.ISNOTIFIED_NO);
    LoanDemandDO loan = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());
    long divisionTemplateLoanBaseId = loan.getDivisionTemplateId();
    DivisionTemplateLoanDO divisionTemplateLoan = divisionTemplateLoanService
            .getByBaseId(divisionTemplateLoanBaseId);
    List<DivsionRuleRole> investRolelist = divisionService
            .getRuleRole(String.valueOf(divisionTemplateLoan.getInvestTemplateId()));
    // ??
    double countInvestCutAmount = 0;
    if (investRolelist != null && investRolelist.size() > 0) {
        for (DivsionRuleRole roleRule : investRolelist) {
            if (DivisionPhaseEnum.INVESET_PHASE.code().equals(roleRule.getPhase())) {
                BigDecimal bg = new BigDecimal(getDaysRuleRate(roleRule.getRule(), trade));
                double rate = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                countInvestCutAmount += Math.round(rate * trade.getLoanedAmount());
            }
        }
    }
    tradeDetailDao.addTradeDetail(new TradeDetail(getYrdExchangeUserId(), trade.getId(),
            (long) countInvestCutAmount, SysUserRoleEnum.PLATFORM.getValue(),
            DivisionPhaseEnum.INVESET_TRANSITION_PHASE.code(), null));
    /** ? */
    List<DivsionRuleRole> repayRolelist = divisionService
            .getRuleRole(String.valueOf(divisionTemplateLoan.getRepayTemplateId()));
    double repayCutAmount = 0;
    if (repayRolelist != null && repayRolelist.size() > 0) {
        for (DivsionRuleRole druleRole : repayRolelist) {
            if (DivisionPhaseEnum.REPAY_PHASE.code().equals(druleRole.getPhase())) {
                BigDecimal bg = new BigDecimal(getDaysRuleRate(druleRole.getRule(), trade));
                repayCutAmount += Math.round(
                        trade.getLoanedAmount() * bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }
    }
    long repayAmount = trade.getLoanedAmount() + (long) repayCutAmount;
    tradeDetailDao.addTradeDetail(new TradeDetail(getYrdExchangeUserId(), trade.getId(), repayAmount,
            SysUserRoleEnum.PLATFORM.getValue(), DivisionPhaseEnum.REPAY_TRANSITION_PHASE.code(), null));
    // ??????
    investRolelist.addAll(repayRolelist);
    if (investRolelist != null && investRolelist.size() > 0) {
        // 
        for (DivsionRuleRole roleRule : investRolelist) {
            logger.info("getGuaranteeRoleId=" + getGuaranteeRoleId() + " roleRule=" + roleRule.getRoleId());
            if (getGuaranteeRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.floor(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(loan.getGuaranteeId(), trade.getId(),
                        (long) amount, 8, roleRule.getPhase(), "")); // loan.getGuaranteeStatement()
                // //?? ??
            } else if (getSponsorRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.floor(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(loan.getSponsorId(), trade.getId(), (long) amount,
                        9, roleRule.getPhase(), "")); // loan.getGuaranteeStatement()
                // //?? ??
            } else if (getPlatformRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.round(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(getYrdUserId(), trade.getId(), (long) amount, 7,
                        roleRule.getPhase(), null));
            }
        }
    }

    // ?
    modifyStatus(trade.getId(), YrdConstants.TradeStatus.GUARANTEE_AUDITING);

    if (sysFunctionConfigService.isTradeFeeCharge()) {
    }

    // ??
    StringBuilder message = new StringBuilder();
    String content = YrdConstants.MessageNotifyConstants.DEMAND_CONFIRMED_NOTIFY;
    UserBaseInfoDO toUser = new UserBaseInfoDO();
    content = content.replace("var1", trade.getName());
    content = content.replace("var2", MoneyUtil.getFormatAmount(trade.getAmount()));
    content = content.replace("var3", MoneyUtil.getFormatAmount(trade.getLoanedAmount()));
    message.append(content);
    setToUserDetail(toUser);
    messageService.notifyUser(toUser, message.toString());
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedTotalIndirect() {
    BigDecimal anticipatedTotalIndirect = null;
    if (awardAmountInfo.getAnticipatedTotalIndirect() != null) {
        BigDecimal bdecAnticipatedTotalIndirect = new BigDecimal(
                awardAmountInfo.getAnticipatedTotalIndirect().doubleValue());
        anticipatedTotalIndirect = bdecAnticipatedTotalIndirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//from   w  w  w  . j  av a2s .  co m
    return anticipatedTotalIndirect;
}

From source file:org.kuali.kfs.module.ar.document.service.impl.ContractsGrantsInvoiceDocumentServiceImpl.java

/**
 * @see org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService#prorateBill(org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument)
 *///from  w  w w.j  a  v a  2s.  c o m
@Override
public void prorateBill(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument)
        throws WorkflowException {
    KualiDecimal totalCost = new KualiDecimal(0); // Amount to be billed on this invoice
    // must iterate through the invoice details because the user might have manually changed the value
    for (ContractsGrantsInvoiceDetail invD : contractsGrantsInvoiceDocument.getInvoiceDetails()) {
        totalCost = totalCost.add(invD.getInvoiceAmount());
    }
    KualiDecimal billedTotalCost = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail()
            .getTotalPreviouslyBilled(); // Total Billed so far
    KualiDecimal accountAwardTotal = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAwardTotal(); // AwardTotal

    if (accountAwardTotal.subtract(billedTotalCost).isGreaterEqual(new KualiDecimal(0))) {
        KualiDecimal amountEligibleForBilling = accountAwardTotal.subtract(billedTotalCost);
        // only recalculate if the current invoice is over what's billable.

        if (totalCost.isGreaterThan(amountEligibleForBilling)) {
            // use BigDecimal because percentage should not have only a scale of 2, we need more for accuracy
            BigDecimal percentage = amountEligibleForBilling.bigDecimalValue()
                    .divide(totalCost.bigDecimalValue(), 10, BigDecimal.ROUND_HALF_DOWN);
            KualiDecimal amountToBill = new KualiDecimal(0); // use to check if rounding has left a few cents off

            ContractsGrantsInvoiceDetail largestCostCategory = null;
            BigDecimal largestAmount = BigDecimal.ZERO;
            for (ContractsGrantsInvoiceDetail invD : contractsGrantsInvoiceDocument.getInvoiceDetails()) {
                BigDecimal newValue = invD.getInvoiceAmount().bigDecimalValue().multiply(percentage);
                KualiDecimal newKualiDecimalValue = new KualiDecimal(
                        newValue.setScale(2, BigDecimal.ROUND_DOWN));
                invD.setInvoiceAmount(newKualiDecimalValue);
                amountToBill = amountToBill.add(newKualiDecimalValue);
                if (newValue.compareTo(largestAmount) > 0) {
                    largestAmount = newKualiDecimalValue.bigDecimalValue();
                    largestCostCategory = invD;
                }
            }
            if (!amountToBill.equals(amountEligibleForBilling)) {
                KualiDecimal remaining = amountEligibleForBilling.subtract(amountToBill);
                if (ObjectUtils.isNull(largestCostCategory)
                        && CollectionUtils.isNotEmpty(contractsGrantsInvoiceDocument.getInvoiceDetails())) {
                    largestCostCategory = contractsGrantsInvoiceDocument.getInvoiceDetails().get(0);
                }
                if (ObjectUtils.isNotNull(largestCostCategory)) {
                    largestCostCategory.setInvoiceAmount(largestCostCategory.getInvoiceAmount().add(remaining));
                }
            }
            recalculateTotalAmountBilledToDate(contractsGrantsInvoiceDocument);
        }
    }
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param yearId// w  ww.j  a v a 2  s  .  com
 * @param monthId
 * @param costCentreId
 * @param empcntClientProjectDataList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeOne
 * @param assistedTimeOne
 * @param apportionedTimeOne
 * @param totalTimeOne
 */
private void getZeroProjectsDetail(Integer yearId, Integer monthId, String costCentreId,
        List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero,
        BigDecimal assistedTimeZero, BigDecimal apportionedTimeOne, BigDecimal totalTimeOne,
        Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getZeroProjectsDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getZeroProjectsDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());
    if (projectIdList.isEmpty()) {
        BigDecimal remainProportion = BigDecimal.ONE;
        Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee,
                month, year, costCentre, countType, remainProportion, assignedProjectsHour, countTypeId,
                employeePcTagsTeamStructMap);
    } else {
        // logger.debug("Else Project details present in execution data ===>");
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects

        Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        Map<Integer, Integer> assignedProjectsCompany = new HashMap<Integer, Integer>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjectsHour.put(projectId, hour);
                assignedProjectsCompany.put(projectId, companyId);
            }

        }
        /*
         * Do the calculation as per time spent on projects and put it to
         * assisted count
         */
        // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)");
        if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
            // logger.debug("Worked hours===> >=168");
            for (Integer key : assignedProjectsCompany.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("1254 :Both in assigned and unassigned projects======>"+totalTimeOne);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedTimeZero, apportionedTimeOne, totalTimeOne);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
        } else {
            // logger.debug("Worked hours===> <168");
            BigDecimal revenueProportion = BigDecimal.ZERO;

            for (Integer key : assignedProjectsHour.keySet()) {
                Integer projectId = key;
                // logger.debug("projectId===> "+projectId);
                BigDecimal timeByProject = assignedProjectsHour.get(key);
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("timeByProject===> "+timeByProject);
                BigDecimal assistedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                assistedHours = assistedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("assignedProjectsHour===> "+assingnedHours);
                revenueProportion = revenueProportion.add(assistedHours);
                logger.debug("1338 :======>" + revenueProportion);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedHours, allignedTimeZero, assistedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
            /*
             * Revenue count put it to apportioned count
             */
            // logger.debug("revenueProportion===> "+revenueProportion);
            if (revenueProportion.compareTo(BigDecimal.ONE) == -1) {
                BigDecimal remainProportion = BigDecimal.ONE.subtract(revenueProportion);
                logger.debug("remainProportion===> " + remainProportion);
                getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                        employee, month, year, costCentre, countType, remainProportion, assignedProjectsHour,
                        countTypeId, employeePcTagsTeamStructMap);
            }
        }
    }
    // logger.debug("<====getZeroProjectDetail END====>");
}

From source file:org.egov.ptis.domain.service.transfer.PropertyTransferService.java

/**
 * API to calculate mutation fee/*from  w w  w .j  ava  2s .co m*/
 *
 * @param partyValue
 * @param departmentValue
 * @return MutationFee
 */
public BigDecimal calculateMutationFee(final BigDecimal partyValue, final BigDecimal departmentValue) {
    BigDecimal mutationFee = BigDecimal.ZERO;
    BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue;

    if (documentValue.compareTo(BigDecimal.ZERO) > 0) {
        List<MutationFeeDetails> mutationFeeDetailsList = mutationFeeRepository.getMutationFee(documentValue);
        if (!mutationFeeDetailsList.isEmpty()) {
            MutationFeeDetails mutationFeeDetails = mutationFeeDetailsList.get(0);
            if (mutationFeeDetails != null) {
                if (mutationFeeDetails.getFlatAmount() != null
                        && mutationFeeDetails.getFlatAmount().compareTo(BigDecimal.ZERO) > 0)
                    if ("N".equalsIgnoreCase(mutationFeeDetails.getIsRecursive().toString()))
                        mutationFee = mutationFeeDetails.getFlatAmount();
                    else {
                        BigDecimal excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit())
                                .add(BigDecimal.ONE);
                        BigDecimal multiplicationFactor = excessDocValue
                                .divide(mutationFeeDetails.getRecursiveFactor(), BigDecimal.ROUND_CEILING);
                        mutationFee = mutationFeeDetails.getFlatAmount()
                                .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveAmount()));
                    }
                if (mutationFeeDetails.getPercentage() != null
                        && mutationFeeDetails.getPercentage().compareTo(BigDecimal.ZERO) > 0
                        && mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase("N"))
                    mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage())
                            .divide(PropertyTaxConstants.BIGDECIMAL_100);
            }
        }
    }
    return mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getObligatedChange() {
    BigDecimal obligatedChange = null;
    if (awardAmountInfo.getObligatedChange() != null) {
        obligatedChange = awardAmountInfo.getObligatedChange().bigDecimalValue();
        obligatedChange = obligatedChange.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }// w  w  w .j  a  v a 2  s.c o m
    return obligatedChange;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedChange() {
    BigDecimal anticipatedChange = null;
    if (awardAmountInfo.getAnticipatedChange() != null) {
        anticipatedChange = awardAmountInfo.getAnticipatedChange().bigDecimalValue();
        anticipatedChange = anticipatedChange.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//  ww w  .j a v a  2 s.c om
    return anticipatedChange;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAmtObligatedToDate() {
    BigDecimal amtObligatedToDate = null;
    if (awardAmountInfo.getAmountObligatedToDate() != null) {
        amtObligatedToDate = awardAmountInfo.getAmountObligatedToDate().bigDecimalValue();
        amtObligatedToDate = amtObligatedToDate.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//  w  ww  .jav  a 2 s  .  c  o  m
    return amtObligatedToDate;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedTotalAmount() {
    BigDecimal anticipatedTotalAmt = null;
    if (awardAmountInfo.getAnticipatedTotalAmount() != null) {
        anticipatedTotalAmt = awardAmountInfo.getAnticipatedTotalAmount().bigDecimalValue();
        anticipatedTotalAmt = anticipatedTotalAmt.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }/*from  w  w w .jav  a 2s  .  c o m*/
    return anticipatedTotalAmt;
}