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

public BigDecimal setScale(int newScale) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal 's.

Usage

From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java

protected LeaveSummary getLeaveSummary(String principalId, LocalDate startDate, LocalDate endDate,
        String accrualCategory, boolean includeFuture) {
    LeaveSummary ls = new LeaveSummary();
    List<LeaveSummaryRow> rows = new ArrayList<LeaveSummaryRow>();

    if (StringUtils.isEmpty(principalId) || startDate == null || endDate == null) {
        return ls;
    }//from   w w w. jav a2  s  . c o m

    Set<String> leavePlans = getLeavePlans(principalId, startDate, endDate);
    PrincipalHRAttributes pha = getPrincipalHrAttributes(principalId, startDate, endDate);
    if (CollectionUtils.isNotEmpty(leavePlans)) {
        List<LeavePlan> leavePlanList = HrServiceLocator.getLeavePlanService()
                .getLeavePlans(new ArrayList<String>(leavePlans), startDate);
        if (CollectionUtils.isNotEmpty(leavePlanList)) {
            LeaveCalendarDocumentHeader approvedLcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
                    .getMaxEndDateApprovedLeaveCalendar(principalId);
            //until we have something that creates carry over, we need to grab everything.
            // Calculating leave bLocks from Calendar Year start instead of Service Date
            Map<String, LeaveBlock> carryOverBlocks = getLeaveBlockService().getLastCarryOverBlocks(principalId,
                    startDate);
            for (LeavePlan lp : leavePlanList) {
                DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d");
                DateTimeFormatter formatter2 = DateTimeFormat.forPattern("MMMM d yyyy");
                DateTime entryEndDate = endDate.toDateTimeAtStartOfDay();
                if (entryEndDate.getHourOfDay() == 0) {
                    entryEndDate = entryEndDate.minusDays(1);
                }
                String aString = formatter.print(startDate) + " - " + formatter2.print(entryEndDate);
                ls.setPendingDatesString(aString);

                if (approvedLcdh != null) {
                    DateTime endApprovedDate = approvedLcdh.getEndDateTime();
                    LocalDateTime aLocalTime = approvedLcdh.getEndDateTime().toLocalDateTime();
                    DateTime endApprovedTime = aLocalTime
                            .toDateTime(HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
                    if (endApprovedTime.getHourOfDay() == 0) {
                        endApprovedDate = endApprovedDate.minusDays(1);
                    }
                    String datesString = formatter.print(approvedLcdh.getBeginDateTime()) + " - "
                            + formatter2.print(endApprovedDate);
                    ls.setYtdDatesString(datesString);
                }

                boolean filterByAccrualCategory = false;
                if (StringUtils.isNotEmpty(accrualCategory)) {
                    filterByAccrualCategory = true;
                    //remove unwanted carry over blocks from map
                    LeaveBlock carryOverBlock = carryOverBlocks.get(accrualCategory);
                    carryOverBlocks = new HashMap<String, LeaveBlock>(1);
                    if (ObjectUtils.isNotNull(carryOverBlock)) {
                        carryOverBlocks.put(carryOverBlock.getAccrualCategory(), carryOverBlock);
                    }
                }
                List<LeaveBlock> leaveBlocks = getLeaveBlockService().getLeaveBlocksSinceCarryOver(principalId,
                        carryOverBlocks, endDate, filterByAccrualCategory);

                List<LeaveBlock> futureLeaveBlocks = new ArrayList<LeaveBlock>();
                if (includeFuture) {
                    if (!filterByAccrualCategory) {
                        futureLeaveBlocks = getLeaveBlockService().getLeaveBlocks(principalId, endDate,
                                endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())));
                    } else {
                        futureLeaveBlocks = getLeaveBlockService().getLeaveBlocksWithAccrualCategory(
                                principalId, endDate,
                                endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())), accrualCategory);
                    }
                }
                Map<String, List<LeaveBlock>> leaveBlockMap = mapLeaveBlocksByAccrualCategory(leaveBlocks);
                Map<String, List<LeaveBlock>> futureLeaveBlockMap = mapLeaveBlocksByAccrualCategory(
                        futureLeaveBlocks);
                List<AccrualCategory> acList = HrServiceLocator.getAccrualCategoryService()
                        .getActiveAccrualCategoriesForLeavePlan(lp.getLeavePlan(), endDate);
                if (CollectionUtils.isNotEmpty(acList)) {
                    for (AccrualCategory ac : acList) {
                        if (ac.getShowOnGrid().equals("Y")) {

                            LeaveSummaryRow lsr = new LeaveSummaryRow();
                            lsr.setAccrualCategory(ac.getAccrualCategory());
                            lsr.setAccrualCategoryId(ac.getLmAccrualCategoryId());
                            //get max balances
                            AccrualCategoryRule acRule = HrServiceLocator.getAccrualCategoryRuleService()
                                    .getAccrualCategoryRuleForDate(ac, endDate, pha.getServiceLocalDate());
                            //accrual category rule id set on a leave summary row will be useful in generating a relevant balance transfer
                            //document from the leave calendar display. Could put this id in the request for balance transfer document.
                            EmployeeOverrideContract maxUsageOverride = LmServiceLocator
                                    .getEmployeeOverrideService().getEmployeeOverride(principalId,
                                            lp.getLeavePlan(), ac.getAccrualCategory(), "MU", endDate);

                            lsr.setAccrualCategoryRuleId(
                                    acRule == null ? null : acRule.getLmAccrualCategoryRuleId());
                            if (acRule != null
                                    && (acRule.getMaxBalance() != null || acRule.getMaxUsage() != null)) {
                                if (acRule.getMaxUsage() != null) {
                                    lsr.setUsageLimit(new BigDecimal(acRule.getMaxUsage()).setScale(2));
                                    ls.setUsageLimit(true);
                                } else {
                                    lsr.setUsageLimit(null);
                                }

                            } else {
                                lsr.setUsageLimit(null);
                            }

                            if (maxUsageOverride != null)
                                lsr.setUsageLimit(new BigDecimal(maxUsageOverride.getOverrideValue()));

                            //Fetching leaveblocks for accCat with type CarryOver -- This is logic according to the CO blocks created from scheduler job.
                            BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                            lsr.setCarryOver(carryOver);

                            //handle up to current leave blocks
                            //CalendarEntry.getEndPeriodDate passed to fetch leave block amounts on last day of Calendar period
                            assignApprovedValuesToRow(lsr, ac.getAccrualCategory(),
                                    leaveBlockMap.get(ac.getAccrualCategory()), lp, startDate, endDate);

                            //how about the leave blocks on the calendar entry being currently handled??
                            /*                            if(carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                                           LeaveBlock carryOverBlock = carryOverBlocks.get(lsr.getAccrualCategory());
                                                           DateTime carryOverBlockLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), carryOverBlock.getLeaveDate());
                                                           DateTime currentLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), TKUtils.getCurrentDate());
                                                           if(carryOverBlockLPStart.equals(currentLPStart))
                             carryOver = carryOverBlock.getLeaveAmount();
                                                        }*/
                            //figure out past carry over values!!!
                            //We now have list of past years accrual and use (with ordered keys!!!)

                            //merge key sets
                            if (carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                carryOver = carryOverBlocks.get(lsr.getAccrualCategory()).getLeaveAmount();
                                carryOver = carryOver.setScale(2);
                            }
                            Set<String> keyset = new HashSet<String>();
                            keyset.addAll(lsr.getPriorYearsUsage().keySet());
                            keyset.addAll(lsr.getPriorYearsTotalAccrued().keySet());
                            EmployeeOverrideContract carryOverOverride = LmServiceLocator
                                    .getEmployeeOverrideService().getEmployeeOverride(principalId,
                                            lp.getLeavePlan(), ac.getAccrualCategory(), "MAC", endDate);

                            for (String key : keyset) {
                                BigDecimal value = lsr.getPriorYearsTotalAccrued().get(key);
                                if (value == null) {
                                    value = BigDecimal.ZERO;
                                }
                                carryOver = carryOver.add(value);
                                BigDecimal use = lsr.getPriorYearsUsage().containsKey(key)
                                        ? lsr.getPriorYearsUsage().get(key)
                                        : BigDecimal.ZERO;
                                carryOver = carryOver.add(use);
                                if (acRule != null && acRule.getMaxCarryOver() != null) {
                                    BigDecimal carryOverDisplay = BigDecimal.ZERO;
                                    if (carryOverOverride != null) {
                                        carryOverDisplay = new BigDecimal(
                                                carryOverOverride.getOverrideValue() < carryOver.longValue()
                                                        ? carryOverOverride.getOverrideValue()
                                                        : carryOver.longValue());
                                    } else {
                                        carryOverDisplay = new BigDecimal(
                                                acRule.getMaxCarryOver() < carryOver.longValue()
                                                        ? acRule.getMaxCarryOver()
                                                        : carryOver.longValue());
                                    }
                                    carryOver = carryOverDisplay;
                                }
                            }

                            lsr.setCarryOver(carryOver);
                            if (acRule != null && acRule.getMaxCarryOver() != null) {
                                if (carryOverOverride != null) {
                                    lsr.setMaxCarryOver(new BigDecimal(carryOverOverride.getOverrideValue()));
                                } else {
                                    lsr.setMaxCarryOver(
                                            new BigDecimal(acRule.getMaxCarryOver() < carryOver.longValue()
                                                    ? acRule.getMaxCarryOver()
                                                    : carryOver.longValue()));
                                }
                            }

                            //handle future leave blocks
                            assignPendingValuesToRow(lsr, ac.getAccrualCategory(),
                                    futureLeaveBlockMap.get(ac.getAccrualCategory()));

                            //compute Leave Balance
                            BigDecimal leaveBalance = lsr.getAccruedBalance()
                                    .subtract(lsr.getPendingLeaveRequests());
                            //if leave balance is set
                            //Employee overrides have already been taken into consideration and the appropriate values
                            //for usage have been set by this point.
                            //                            if (acRule != null && StringUtils.equals(acRule.getMaxBalFlag(), "Y")) {
                            //there exists an accrual category rule with max balance limit imposed.
                            //max bal flag = 'Y' has no precedence here with max-bal / balance transfers implemented.
                            //unless institutions are not required to define a max balance limit for action_at_max_bal = LOSE.
                            //Possibly preferable to procure forfeiture blocks through balance transfer
                            if (lsr.getUsageLimit() != null) { //should not set leave balance to usage limit simply because it's not null.
                                BigDecimal availableUsage = lsr.getUsageLimit()
                                        .subtract(lsr.getYtdApprovedUsage().add(lsr.getPendingLeaveRequests()));
                                if (leaveBalance.compareTo(availableUsage) > 0)
                                    lsr.setLeaveBalance(availableUsage);
                                else
                                    lsr.setLeaveBalance(leaveBalance);
                            } else { //no usage limit
                                lsr.setLeaveBalance(leaveBalance);
                            }

                            rows.add(lsr);
                        }
                    }
                    // let's check for 'empty' accrual categories
                    if (leaveBlockMap.containsKey(null) || futureLeaveBlockMap.containsKey(null)) {
                        LeaveSummaryRow otherLeaveSummary = new LeaveSummaryRow();
                        //otherLeaveSummary.setAccrualCategory("Other");

                        assignApprovedValuesToRow(otherLeaveSummary, null, leaveBlockMap.get(null), lp,
                                startDate, endDate);
                        BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                        for (Map.Entry<String, BigDecimal> entry : otherLeaveSummary.getPriorYearsTotalAccrued()
                                .entrySet()) {
                            carryOver = carryOver.add(entry.getValue());
                            BigDecimal use = otherLeaveSummary.getPriorYearsUsage().containsKey(entry.getKey())
                                    ? otherLeaveSummary.getPriorYearsUsage().get(entry.getKey())
                                    : BigDecimal.ZERO;
                            carryOver = carryOver.add(use);
                        }
                        otherLeaveSummary.setCarryOver(carryOver);
                        assignPendingValuesToRow(otherLeaveSummary, null, futureLeaveBlockMap.get(null));
                        otherLeaveSummary.setAccrualCategory("Other");

                        //compute Leave Balance
                        // blank the avail
                        otherLeaveSummary.setUsageLimit(null);
                        otherLeaveSummary.setLeaveBalance(null);

                        rows.add(otherLeaveSummary);
                    }
                }
            }
        }
    }
    ls.setLeaveSummaryRows(rows);
    return ls;
}

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

/**
 * {@inheritDoc}//from  w  w  w .j  av  a  2  s  .  c  o m
 */
// This method needs to be non-transaction in ensure correct creation of position and cash balance records in a separate transaction
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override
public void createTransaction(final long securityId, final String strategyName, final String extId,
        final Date dateTime, final long quantity, final BigDecimal price, final BigDecimal executionCommission,
        final BigDecimal clearingCommission, final BigDecimal fee, final Currency currency,
        final TransactionType transactionType, final String accountName, final String description) {

    Validate.notEmpty(strategyName, "Strategy name is empty");
    Validate.notNull(dateTime, "Date time is null");
    Validate.notNull(price, "Price is null");
    Validate.notNull(transactionType, "Transaction type is null");

    Currency currencyNonFinal = currency;
    long quantityNonFinal = quantity;
    // validations

    Strategy strategy = this.strategyDao.findByName(strategyName);
    if (strategy == null) {
        throw new ServiceException("strategy " + strategyName + " was not found", null);
    }

    int scale = this.commonConfig.getPortfolioDigits();
    Security security = this.securityDao.get(securityId);
    if (TransactionType.BUY.equals(transactionType) || TransactionType.SELL.equals(transactionType)
            || TransactionType.EXPIRATION.equals(transactionType)
            || TransactionType.TRANSFER.equals(transactionType)) {

        if (security == null) {
            throw new IllegalArgumentException("security " + securityId + " was not found");
        }

        currencyNonFinal = security.getSecurityFamily().getCurrency();
        scale = security.getSecurityFamily().getScale();

        if (TransactionType.BUY.equals(transactionType)) {
            quantityNonFinal = Math.abs(quantityNonFinal);
        } else if (TransactionType.SELL.equals(transactionType)) {
            quantityNonFinal = -Math.abs(quantityNonFinal);
        }

        // for EXPIRATION or TRANSFER the actual quantity istaken

    } else if (TransactionType.CREDIT.equals(transactionType)
            || TransactionType.INTREST_RECEIVED.equals(transactionType)
            || TransactionType.DIVIDEND.equals(transactionType)
            || TransactionType.REFUND.equals(transactionType)) {

        if (currencyNonFinal == null) {
            throw new IllegalArgumentException("need to define a currency for " + transactionType);
        }

        quantityNonFinal = 1;

    } else if (TransactionType.DEBIT.equals(transactionType)
            || TransactionType.INTREST_PAID.equals(transactionType)
            || TransactionType.FEES.equals(transactionType)) {

        if (currencyNonFinal == null) {
            throw new IllegalArgumentException("need to define a currency for " + transactionType);
        }

        quantityNonFinal = -1;

    } else if (TransactionType.REBALANCE.equals(transactionType)) {

        throw new IllegalArgumentException("transaction type REBALANCE not allowed");
    }

    Account account = accountName != null ? this.accountDao.findByName(accountName) : null;

    // create the transaction
    Transaction transaction = Transaction.Factory.newInstance();
    transaction.setUuid(UUID.randomUUID().toString());
    transaction.setDateTime(dateTime);
    transaction.setExtId(extId);
    transaction.setQuantity(quantityNonFinal);
    transaction.setPrice(price.setScale(scale));
    transaction.setType(transactionType);
    transaction.setSecurity(security);
    transaction.setStrategy(strategy);
    transaction.setCurrency(currencyNonFinal);
    transaction.setExecutionCommission(executionCommission);
    transaction.setClearingCommission(clearingCommission);
    transaction.setFee(fee);
    transaction.setAccount(account);
    transaction.setDescription(description);

    processTransaction(transaction);

}

From source file:com.ibm.soatf.component.soap.builder.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;//from  w  w  w  .j  ava2 s. co m
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuilder sb = new StringBuilder(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuilder sb = new StringBuilder("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

From source file:com.centeractive.ws.builder.soap.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;/*from   w  ww  .  ja  va 2  s . c om*/
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuffer sb = new StringBuffer(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuffer sb = new StringBuffer("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

From source file:org.egov.egf.commons.EgovCommon.java

public BigDecimal getAccCodeBalanceForIndirectExpense(final Date asondate, final String glcode,
        final Integer accountdetailType, final String accountdetailkey) throws ValidationException, Exception {
    LOGGER.debug("EgovCommon | getAccCodeBalanceForIndirectExpense | Start");
    validateParameterData(asondate, glcode, accountdetailType, accountdetailkey);
    final StringBuffer glCodeBalQry = new StringBuffer(400);
    final StringBuffer glCodeDbtBalQry = new StringBuffer(400);
    final StringBuffer glCodeCrdBalQry = new StringBuffer(400);
    BigDecimal glCodeBalance = BigDecimal.ZERO;
    BigDecimal subledgerDbtBalance = BigDecimal.ZERO;
    BigDecimal subledgerCrdBalance = BigDecimal.ZERO;

    final List<AppConfigValues> appList = appConfigValuesService
            .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, "statusexcludeReport");
    final String statusExclude = appList.get(0).getValue();
    if (null == accountdetailType && null == accountdetailkey) {
        glCodeBalQry.append(//w w  w  .  j  a  v  a 2  s. c  o  m
                "SELECT (case when sum(gl.debitAmount)=null then 0 else sum(gl.debitAmount) end - case when sum(gl.creditAmount)  = null then 0 else sum(gl.creditAmount) end)")
                .append(" as amount FROM  CGeneralLedger gl , CVoucherHeader vh WHERE  gl.voucherHeaderId.id=vh.id and gl.glcodeId.glcode=?")
                .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where  startingDate <= '")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (")
                .append(statusExclude)
                .append(") and ((vh.name='Contractor Journal' and state_id is null) or(vh.name !='Contractor Journal' and vh.name !='CapitalisedAsset' ) )");

        final List<Object> list = getPersistenceService().findAllBy(glCodeBalQry.toString(), glcode);
        glCodeBalance = BigDecimal.valueOf((Double) list.get(0));
    } else {
        // Getting the debit balance.
        glCodeDbtBalQry.append(
                "SELECT sum(gld.amount)  as debitamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld")
                .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=?  ")
                .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where  startingDate <= '")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (")
                .append(statusExclude)
                .append(")and ((vh.name='Contractor Journal' and state_id is null) or(vh.name !='Contractor Journal' and vh.name !='CapitalisedAsset') ) ")
                .append(" and gld.detailTypeId.id =").append(accountdetailType);
        if (null != accountdetailkey)
            glCodeDbtBalQry.append(" and gld.detailKeyId in (").append(accountdetailkey).append(")");
        glCodeDbtBalQry.append(" and gl.debitAmount >0");
        final List<Object> listDbt = getPersistenceService().findAllBy(glCodeDbtBalQry.toString(), glcode);
        subledgerDbtBalance = (BigDecimal) listDbt.get(0) == null ? BigDecimal.ZERO
                : (BigDecimal) listDbt.get(0);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(" total debit amount :  " + subledgerDbtBalance);

        // get the credit balance

        glCodeCrdBalQry.append(
                "SELECT sum(gld.amount) as creditamount from CVoucherHeader vh , CGeneralLedger gl,CGeneralLedgerDetail gld")
                .append(" WHERE gl.voucherHeaderId.id=vh.id and gl.id = gld.generalLedgerId.id and gl.glcodeId.glcode=?  ")
                .append(" and vh.voucherDate >= (select startingDate from CFinancialYear where  startingDate <= '")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("' AND endingDate >='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("') and vh.voucherDate <='")
                .append(Constants.DDMMYYYYFORMAT1.format(asondate)).append("'and vh.status not in (")
                .append(statusExclude)
                .append(")and ((vh.name='Contractor Journal' and state_id is null) or(vh.name !='Contractor Journal' and vh.name !='CapitalisedAsset' ) )")
                .append(" and gld.detailTypeId.id =").append(accountdetailType);
        if (null != accountdetailkey)
            glCodeCrdBalQry.append(" and gld.detailKeyId in(").append(accountdetailkey).append(")");
        glCodeCrdBalQry.append(" and gl.creditAmount >0");
        final List<Object> listCrd = getPersistenceService().findAllBy(glCodeCrdBalQry.toString(), glcode);
        subledgerCrdBalance = (BigDecimal) listCrd.get(0) == null ? BigDecimal.ZERO
                : (BigDecimal) listCrd.get(0);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(" total credit amount :  " + subledgerCrdBalance);
        glCodeBalance = subledgerDbtBalance.subtract(subledgerCrdBalance);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(" total balance amount :  " + glCodeBalance);

    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("EgovCommon | getAccCodeBalanceForIndirectExpense | End");
    glCodeBalance = glCodeBalance.setScale(2);
    return glCodeBalance;
}

From source file:lasige.steeldb.jdbc.BFTRowSet.java

/**
 * Retrieves the value of the designated column in the current row
 * of this <code>CachedRowSetImpl</code> object as a
 * <code>java.math.BigDecimal</code> object.
 * <P>/*from  w w  w  . j a va  2  s. co  m*/
 * This method is deprecated; use the version of <code>getBigDecimal</code>
 * that does not take a scale parameter and returns a value with full
 * precision.
 *
 * @param columnIndex the first column is <code>1</code>, the second
 *        is <code>2</code>, and so on; must be <code>1</code> or larger
 *        and equal to or less than the number of columns in the rowset
 * @param scale the number of digits to the right of the decimal point in the
 *        value returned
 * @return the column value with the specified number of digits to the right
 *         of the decimal point; if the value is SQL <code>NULL</code>, the
 *         result is <code>null</code>
 * @throws SQLException if the given column index is out of bounds,
 *            the cursor is not on a valid row, or this method fails
 * @deprecated
 */
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
    Object value;
    BigDecimal bDecimal, retVal;

    // sanity check.
    checkIndex(columnIndex);
    // make sure the cursor is on a valid row
    checkCursor();

    setLastValueNull(false);
    value = getCurrentRow().getColumnObject(columnIndex);

    // check for SQL NULL
    if (value == null) {
        setLastValueNull(true);
        return (new BigDecimal(0));
    }

    bDecimal = this.getBigDecimal(columnIndex);

    retVal = bDecimal.setScale(scale);

    return retVal;
}