List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:org.egov.ptis.domain.service.report.ReportService.java
public BigDecimal formatAmt(final double amt) { return BigDecimal.valueOf(amt / 1000).setScale(2, BigDecimal.ROUND_HALF_UP); }
From source file:org.egov.adtax.service.AdvertisementDemandService.java
public EgDemand updateDemand(final AdvertisementPermitDetail advertisementPermitDetail, EgDemand demand) { final Installment installment = getCurrentInstallment(); BigDecimal totalDemandAmount = BigDecimal.ZERO; // Boolean calculateTax=true; Boolean enchroachmentFeeAlreadyExistInDemand = false; final List<EgDemandDetails> removableDemandDetailList = new ArrayList<>(); // EgDemand demand = advertisement.getDemandId(); if (demand == null) demand = createDemand(advertisementPermitDetail); else {/*from w w w . j a v a 2 s . co m*/ final EgDemandReason pendingTaxReason = getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment); final EgDemandReason encroachmentFeeReason = getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment); final EgDemandReason taxReason = getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX, installment); /* * if (advertisementPermitDetail.getTaxAmount() != null || * advertisementPermitDetail.getAdvertisement().getPendingTax() != null) { if * (advertisementPermitDetail.getAdvertisement().getPendingTax() != null) taxAmount = * taxAmount.add(advertisementPermitDetail.getAdvertisement().getPendingTax()); if * (advertisementPermitDetail.getTaxAmount() != null) taxAmount = * taxAmount.add(advertisementPermitDetail.getTaxAmount()); } */ for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails()) { // Assumption: tax amount is mandatory. if (dmdDtl.getEgDemandReason().getId() == taxReason.getId() && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) { // TODO: Also check whether fully collected ? totalDemandAmount = totalDemandAmount .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount())); dmdDtl.setAmount( advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP)); } if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId() && advertisementPermitDetail.getAdvertisement().getPendingTax() != null && advertisementPermitDetail.getAdvertisement().getPendingTax() .compareTo(BigDecimal.ZERO) > 0) { // TODO: Also check whether fully collected ? totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getAdvertisement() .getPendingTax().subtract(dmdDtl.getAmount())); dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0, BigDecimal.ROUND_HALF_UP)); } // Encroachment fee may not mandatory. If already part of demand // then if (dmdDtl.getEgDemandReason().getId() == encroachmentFeeReason.getId()) { enchroachmentFeeAlreadyExistInDemand = true; if (advertisementPermitDetail.getEncroachmentFee() != null && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) { totalDemandAmount = totalDemandAmount .add(advertisementPermitDetail.getEncroachmentFee().subtract(dmdDtl.getAmount())); dmdDtl.setAmount(advertisementPermitDetail.getEncroachmentFee().setScale(0, BigDecimal.ROUND_HALF_UP)); // update encroachment fee.. } else { totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount()); // demand.removeEgDemandDetails(dmdDtl); removableDemandDetailList.add(dmdDtl); // delete demand detail } } } for (final EgDemandDetails removableDmdDtl : removableDemandDetailList) demand.removeEgDemandDetails(removableDmdDtl); if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) { demand.addEgDemandDetails( createDemandDetails(advertisementPermitDetail.getEncroachmentFee(), getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment), BigDecimal.ZERO)); totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee()); // TODO: CHECK WHETHER FULLY PAID IN LEGACY HANDLED. } demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP)); } return demand; }
From source file:org.egov.wtms.web.controller.application.MeterReadingController.java
private BigDecimal calculateDemandWithRecursiveAmount(final UsageSlab usageSlab, final MeteredRatesDetail meteredRatesDetail, final BigDecimal numberOfUnitsPerMonth) { BigDecimal totalAmount = BigDecimal.ZERO; BigDecimal amtValue;//from w w w. j ava2 s. co m BigDecimal amount1; BigDecimal amount2; if (meteredRatesDetail.getFlatAmount() != null && meteredRatesDetail.getFlatAmount() != 0 && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) { amtValue = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume())) .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor()) .setScale(0, BigDecimal.ROUND_HALF_UP)); totalAmount = BigDecimal.valueOf(meteredRatesDetail.getFlatAmount()) .add(amtValue.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount()))); } else if (meteredRatesDetail.getRateAmount() != null && meteredRatesDetail.getRateAmount() != 0 && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) { amount1 = BigDecimal.valueOf(usageSlab.getFromVolume()).subtract(BigDecimal.ONE) .multiply(BigDecimal.valueOf(meteredRatesDetail.getRateAmount())); amount2 = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume())) .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor()), 0, BigDecimal.ROUND_HALF_UP); amtValue = amount2.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())).setScale(0, BigDecimal.ROUND_HALF_UP); totalAmount = amount1.add(amtValue); } return totalAmount; }
From source file:de.forsthaus.webui.InitApplicationCtrl.java
/** * Add a new row to the grid.<br>/* w w w . j ava 2 s. c o m*/ * * @param rowParent * @param tableName * @param value */ private void addNewRow(Rows rowParent, String tableName, Object value) { Row row = new Row(); Html html_TableName = new Html(tableName); html_TableName.setStyle("padding-left: 5px;"); Div divKey = new Div(); divKey.setAlign("left"); divKey.appendChild(html_TableName); Html html_RecordCount = null; if (value instanceof BigDecimal) { BigDecimal myDec = (BigDecimal) value; myDec = myDec.setScale(2, BigDecimal.ROUND_HALF_UP); // Format the value to money NumberFormat formatter = new DecimalFormat("#,##0.00"); String money = formatter.format(myDec); html_RecordCount = new Html(money); } else if (value instanceof Integer) { // Format the value NumberFormat formatter = new DecimalFormat("###,###.###"); String formattedInteger = formatter.format(value); html_RecordCount = new Html(String.valueOf(value)); } else html_RecordCount = new Html(String.valueOf(value)); html_RecordCount.setStyle("padding-right: 5px;"); Div divValue = new Div(); divValue.setAlign("right"); divValue.appendChild(html_RecordCount); row.appendChild(divKey); row.appendChild(divValue); row.setParent(rowParent); }
From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java
/** * Returns Top Ten with ULB wise grouping and total amount aggregation * * @param waterChargedashBoardRequest//w w w.j ava 2 s . co m * @param indexName * @param order * @param orderingAggregationName * @return */ public List<WaterTaxPayerDetails> returnUlbWiseAggregationResults( final WaterChargeDashBoardRequest waterChargedashBoardRequest, final String indexName, final Boolean order, final String orderingAggregationName, final int size, final boolean isBillCollectorWise) { final List<WaterTaxPayerDetails> taxPayers = new ArrayList<>(); Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>(); final BoolQueryBuilder boolQuery = waterChargeCollDocService.prepareWhereClause(waterChargedashBoardRequest, null); CFinancialYear currFinYear = cFinancialYearService.getCurrentFinancialYear(); // orderingAggregationName is the aggregation name by which we have to // order the results // IN this case can be one of "totaldemand" or TOTAL_COLLECTION or // "avg_achievement" String groupingField; if (StringUtils.isNotBlank(waterChargedashBoardRequest.getUlbCode()) || StringUtils .isNotBlank(waterChargedashBoardRequest.getType()) && (waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE) || waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_BILLCOLLECTORWISE))) groupingField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD; else groupingField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD; Long startTime = System.currentTimeMillis(); @SuppressWarnings("rawtypes") AggregationBuilder aggregation; SearchQuery searchQueryColl; // Apply the ordering and max results size only if the type is not // billcollector if (!isBillCollectorWise) { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(size) .order(Terms.Order.aggregation(orderingAggregationName, order)) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .addAggregation(aggregation).build(); } else { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(250) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build(); } final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); // Fetch ward wise Bill Collector details for ward based grouping if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType())) wardWiseBillCollectors = waterChargeCollDocService .getWardWiseBillCollectors(waterChargedashBoardRequest); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by ulbWiseAggregations is (millisecs) : " + timeTaken); WaterTaxPayerDetails taxDetail; startTime = System.currentTimeMillis(); final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate()); final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1); final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1); final StringTerms totalAmountAggr = collAggr.get(AGGREGATION_FIELD); for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) { taxDetail = new WaterTaxPayerDetails(); taxDetail.setRegionName(waterChargedashBoardRequest.getRegionName()); taxDetail.setDistrictName(waterChargedashBoardRequest.getDistrictName()); taxDetail.setUlbGrade(waterChargedashBoardRequest.getUlbGrade()); final String fieldName = String.valueOf(entry.getKey()); if (groupingField.equals(WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD)) { taxDetail.setWardName(fieldName); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType()) && !wardWiseBillCollectors.isEmpty()) taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY : wardWiseBillCollectors.get(fieldName).getBillCollector()); } else taxDetail.setUlbName(fieldName); // Proportional Demand = (totalDemand/12)*noOfmonths final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final Sum totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND); final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION); final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue()) .setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal proportionalDemand = totalDemandValue .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); taxDetail.setTotalDmd(totalDemandValue); taxDetail.setCurrentYearTillDateColl(totalCollections); taxDetail.setCurrentYearTillDateDmd(proportionalDemand); taxDetail.setAchievement(totalCollections.multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); taxDetail.setCurrentYearTillDateBalDmd(proportionalDemand.subtract(totalCollections)); final BigDecimal lastYearCollection = waterChargeCollDocService.getCollectionBetweenDates( waterChargedashBoardRequest, lastYearFromDate, lastYearToDate, fieldName); // variance = ((lastYearCollection/currentYearCollection )*100) BigDecimal variation = BigDecimal.ZERO; taxDetail.setLastYearTillDateColl(lastYearCollection); if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else if (totalCollections.compareTo(BigDecimal.ZERO) > 0) variation = taxDetail.getCurrentYearTillDateColl().subtract(taxDetail.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(taxDetail.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); /* * variation * =taxDetail.getLastYearTillDateColl().multiply(WaterTaxConstants. * BIGDECIMAL_100) .divide(totalCollections, 1, * BigDecimal.ROUND_HALF_UP); */ taxDetail.setLastYearVar(variation); taxPayers.add(taxDetail); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is (millisecs) : " + timeTaken); return returnTopResults(taxPayers, size, order); }
From source file:com.mum.app.AutoSubmitPriceApp.java
public String BuildSubmitPriceXml(Map<String, Float> submitSkuMap) { XmlBuilder xmlBuilder = new XmlBuilder(); xmlBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); xmlBuilder.beginObject("AmazonEnvelope"); xmlBuilder.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlBuilder.writeAttribute("xsi:noNamespaceSchemaLocation", "amznenvelope.xsd"); xmlBuilder.beginObject("Header"); xmlBuilder.write("DocumentVersion", "1.01"); xmlBuilder.write("MerchantIdentifier", AutoSubmitPriceConfig.sellerId); xmlBuilder.endObject("Header"); xmlBuilder.write("MessageType", "Price"); int msgid = 1; for (Entry<String, Float> entry : submitSkuMap.entrySet()) { xmlBuilder.beginObject("Message"); xmlBuilder.write("MessageID", msgid); xmlBuilder.beginObject("Price"); xmlBuilder.write("SKU", entry.getKey()); xmlBuilder.beginObject("StandardPrice"); xmlBuilder.writeAttribute("currency", "USD"); //// w ww .j av a 2s . c om BigDecimal b = new BigDecimal(entry.getValue()); Float fvalue = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); xmlBuilder.writeValue(fvalue.toString()); xmlBuilder.endObject("StandardPrice"); xmlBuilder.endObject("Price"); xmlBuilder.endObject("Message"); msgid++; } xmlBuilder.endObject("AmazonEnvelope"); return xmlBuilder.toString(); }
From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java
/** * @param _parameter Parameter as passed by the eFasp API * @return new Return//from w w w . ja v a2s . c o m * @throws EFapsException on error */ public Return createGainLoss4SimpleAccount(final Parameter _parameter) throws EFapsException { final PrintQuery printPer = new PrintQuery(_parameter.getInstance()); final SelectBuilder selCurrInst = SelectBuilder.get().linkto(CIAccounting.Period.CurrencyLink).instance(); printPer.addSelect(selCurrInst); printPer.addAttribute(CIAccounting.Period.FromDate, CIAccounting.Period.CurrencyLink); printPer.execute(); final DateTime dateFrom = printPer.<DateTime>getAttribute(CIAccounting.Period.FromDate); final Instance currencyInst = printPer.<Instance>getSelect(selCurrInst); final String[] relOIDs = (String[]) Context.getThreadContext() .getSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name); final DateTime dateTo = new DateTime(_parameter .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.transactionDate.name)); final DateTime dateEx = new DateTime(_parameter .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.exchangeDate.name)); Insert insert = null; BigDecimal totalSum = BigDecimal.ZERO; for (final String oid : relOIDs) { Instance tarCurInst = null; final Instance relInst = Instance.get(oid); final PrintQuery print = new PrintQuery(relInst); final SelectBuilder selAccount = new SelectBuilder() .linkto(CIAccounting.AccountConfigSimple2Period.FromLink).oid(); print.addSelect(selAccount); print.addAttribute(CIAccounting.AccountConfigSimple2Period.IsSale); if (print.execute()) { final Instance instAcc = Instance.get(print.<String>getSelect(selAccount)); final boolean isSale = print.<Boolean>getAttribute(CIAccounting.AccountConfigSimple2Period.IsSale); final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction); attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink, _parameter.getInstance()); attrQuerBldr.addWhereAttrGreaterValue(CIAccounting.Transaction.Date, dateFrom.minusMinutes(1)); attrQuerBldr.addWhereAttrLessValue(CIAccounting.Transaction.Date, dateTo.plusDays(1)); final AttributeQuery attrQuery = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID); final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, instAcc); queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selTRInst = SelectBuilder.get() .linkto(CIAccounting.TransactionPositionAbstract.RateCurrencyLink).instance(); multi.addSelect(selTRInst); multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount, CIAccounting.TransactionPositionAbstract.RateAmount); BigDecimal gainlossSum = BigDecimal.ZERO; multi.execute(); while (multi.next()) { final BigDecimal oldRateAmount = multi .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount); final BigDecimal oldAmount = multi .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount); final Instance targetCurrInst = multi.<Instance>getSelect(selTRInst); final BigDecimal rate = evaluateRate(_parameter, dateEx, currencyInst, targetCurrInst, isSale); final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP); BigDecimal gainloss = BigDecimal.ZERO; if (!currencyInst.equals(targetCurrInst)) { gainloss = newAmount.subtract(oldAmount); tarCurInst = targetCurrInst; } else { gainloss = newAmount; } gainlossSum = gainlossSum.add(gainloss); } totalSum = totalSum.add(gainlossSum); final Map<String, String[]> map = validateInfo(_parameter, gainlossSum); final String[] accs = map.get("accs"); final String[] check = map.get("check"); if (checkAccounts(accs, 0, check).length() > 0) { if (gainlossSum.compareTo(BigDecimal.ZERO) != 0) { final String[] accOids = map.get("accountOids"); if (insert == null) { final String descr = DBProperties.getFormatedDBProperty( Recalculate.class.getName() + ".gainLoss4SimpleAccountTransDesc", dateTo.toDate()); insert = new Insert(CIAccounting.Transaction); insert.add(CIAccounting.Transaction.Description, descr); insert.add(CIAccounting.Transaction.Date, dateTo); insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance()); insert.add(CIAccounting.Transaction.Status, Status.find(CIAccounting.TransactionStatus.Open)); insert.execute(); } Insert insertPos = new Insert(CIAccounting.TransactionPositionDebit); insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getInstance()); if (gainlossSum.signum() > 0) { insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, Instance.get(accOids[0])); } else { insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc); } insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainlossSum.abs().negate()); insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount, BigDecimal.ZERO); insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currencyInst); insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, tarCurInst); insertPos.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); insertPos.execute(); insertPos = new Insert(CIAccounting.TransactionPositionCredit); insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getInstance()); if (gainlossSum.signum() > 0) { insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc); } else { insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, Instance.get(accOids[0])); } insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainlossSum.abs()); insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, BigDecimal.ZERO); insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink, currencyInst); insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, tarCurInst); insertPos.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); insertPos.execute(); } } } } if (insert != null) { final Instance instance = insert.getInstance(); // create classifications final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType(); final Insert relInsert1 = new Insert(classification1.getClassifyRelationType()); relInsert1.add(classification1.getRelLinkAttributeName(), instance); relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId()); relInsert1.execute(); final Insert classInsert1 = new Insert(classification1); classInsert1.add(classification1.getLinkAttributeName(), instance); classInsert1.execute(); final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss.getType(); final Insert relInsert = new Insert(classification.getClassifyRelationType()); relInsert.add(classification.getRelLinkAttributeName(), instance); relInsert.add(classification.getRelTypeAttributeName(), classification.getId()); relInsert.execute(); final Insert classInsert = new Insert(classification); classInsert.add(classification.getLinkAttributeName(), instance); classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, totalSum); classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, totalSum); classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, currencyInst); classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink, currencyInst); classInsert.add(CIAccounting.TransactionClassGainLoss.Rate, new Object[] { BigDecimal.ONE, BigDecimal.ONE }); classInsert.execute(); } // clean up Context.getThreadContext() .removeSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name); return new Return(); }
From source file:org.fcrepo.client.test.PerformanceTests.java
private static double round(double d) { int decimalPlace = 5; BigDecimal bd = new BigDecimal(Double.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd.doubleValue(); }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
public List<WaterChargeConnectionTypeResponse> getFullCollectionIndexDtlsForCOnnectionType( final WaterChargeDashBoardRequest collectionDetailsRequest) { final List<WaterChargeConnectionTypeResponse> collectionIndexDetailsList = new ArrayList<>(); final WaterChargeConnectionTypeResponse collectionIndexDetails = new WaterChargeConnectionTypeResponse(); Date fromDate;/*from w w w. j a v a 2 s.c om*/ Date toDate; BigDecimal todayColl;// need to test BigDecimal tillDateColl;// need to test final Long startTime = System.currentTimeMillis(); final CFinancialYear financialyear = cFinancialYearService.getCurrentFinancialYear(); /** * As per Elastic Search functionality, to get the total collections * between 2 dates, add a day to the endDate and fetch the results For * Current day's collection if dates are sent in the request, consider * the toDate, else take date range between current date +1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = new Date(); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // Todays collection todayColl = getCollectionBetweenDates(collectionDetailsRequest, fromDate, toDate, null); collectionIndexDetails.setTodayColl(todayColl); // Last year Todays day collection todayColl = getCollectionBetweenDates(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null); collectionIndexDetails.setLastYearTodayColl(todayColl); /** * For collections between the date ranges if dates are sent in the * request, consider the same, else calculate from current year start * date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = DateUtils.startOfDay(financialyear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // Current Year till today collection tillDateColl = getCollectionBetweenDates(collectionDetailsRequest, fromDate, toDate, null); collectionIndexDetails.setCurrentYearTillDateColl(tillDateColl); // Last year till same date of todays date collection tillDateColl = getCollectionBetweenDates(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null); collectionIndexDetails.setLastYearTillDateColl(tillDateColl); final Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getCompleteCollectionIndexDetails() is (millisecs) : " + timeTaken); /** * For fetching total demand between the date ranges if dates are sent * in the request, consider fromDate and toDate+1 , else calculate from * current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), "yyyy-MM-dd"); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), "yyyy-MM-dd"), 1); } else { fromDate = DateUtils.startOfDay(financialyear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // starts from final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(collectionDetailsRequest); if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getTotalDemandBasedOnInputFilters() is (millisecs): " + timeTaken); final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; collectionIndexDetails.setTotalDmd(totalDemand); // Proportional Demand = (totalDemand/12)*noOfmonths final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails .setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails.setPerformance( collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); BigDecimal variation; if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else variation = collectionIndexDetails.getCurrentYearTillDateColl() .subtract(collectionIndexDetails.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); collectionIndexDetails.setLastYearVar(variation); if (LOGGER.isDebugEnabled()) LOGGER.debug( "Time taken for setting values in getConsolidatedDemandInfo() is (millisecs): " + timeTaken); collectionIndexDetailsList.add(collectionIndexDetails); return collectionIndexDetailsList; }
From source file:com.konakart.server.KKGWTServiceImpl.java
/** * Format the price in the OrderProducts * /* w w w . j a v a 2 s . com*/ * @param order * @throws KKGWTException * @throws KKAppException * @throws KKException */ private void formatOrder(OrderIf serverOrder, GWT_Order clientOrder) throws KKGWTException { try { if (serverOrder != null && serverOrder.getOrderProducts() != null) { for (int i = 0; i < serverOrder.getOrderProducts().length; i++) { OrderProductIf serverOP = serverOrder.getOrderProducts()[i]; GWT_OrderProduct clientOP = clientOrder.getOrderProducts()[i]; clientOP.setFormattedTaxRate( serverOP.getTaxRate().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); clientOP.setFormattedFinalPriceIncTax(getAppEng().formatPrice(serverOP.getFinalPriceIncTax())); clientOP.setFormattedFinalPriceExTax(getAppEng().formatPrice(serverOP.getFinalPriceExTax())); } } if (serverOrder != null && serverOrder.getOrderTotals() != null) { for (int i = 0; i < serverOrder.getOrderTotals().length; i++) { OrderTotalIf serverOT = serverOrder.getOrderTotals()[i]; GWT_OrderTotal clientOT = clientOrder.getOrderTotals()[i]; clientOT.setFormattedValue(getAppEng().formatPrice(serverOT.getValue())); } } } catch (KKAppException e) { throw new KKGWTException(getExceptionMessage(e)); } }