List of usage examples for java.math BigDecimal multiply
public BigDecimal multiply(BigDecimal multiplicand)
(this × multiplicand)
, and whose scale is (this.scale() + multiplicand.scale()) . From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java
/** * calculates values for a list of accounting lines based on an amount for proportional method * * @param sourceAccountingLines//from ww w . j a v a 2s. c o m * @param totalAmount */ @Override public <T extends PurApAccountingLine> void updatePreqProporationalAccountAmountsWithTotal( List<T> sourceAccountingLines, KualiDecimal totalAmount) { if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) { KualiDecimal accountTotal = KualiDecimal.ZERO; BigDecimal accountTotalPercent = BigDecimal.ZERO; T lastAccount = null; for (T account : sourceAccountingLines) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()) .divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString())) .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR))); } } if (ObjectUtils.isNotNull(account.getAmount())) { accountTotal = accountTotal.add(account.getAmount()); } if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent()); } lastAccount = account; } // put excess on last account if (lastAccount != null) { KualiDecimal difference = totalAmount.subtract(accountTotal); if (ObjectUtils.isNotNull(lastAccount.getAmount())) { lastAccount.setAmount(lastAccount.getAmount().add(difference)); } BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent) .setScale(BIG_DECIMAL_SCALE); if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) { lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference)); } } } else { for (T account : sourceAccountingLines) { account.setAmount(KualiDecimal.ZERO); } } }
From source file:org.libreplan.business.orders.entities.OrderElement.java
/** * Calculates the budget with the margin {@link Order#getBudgetMargin()} for this orderElement. * * @return calculated budget//from w ww .j a va 2 s . c o m */ private BigDecimal calculateBudgetWithMargin() { BigDecimal margin = this.getOrder().getBudgetMargin() != null ? new BigDecimal(this.getOrder().getBudgetMargin()) : BigDecimal.ZERO; BigDecimal hundred = new BigDecimal(100); BigDecimal budget = getBudget(); BigDecimal marginBudget = budget.multiply(margin).divide(hundred, 2, BigDecimal.ROUND_HALF_EVEN); return budget.add(marginBudget); }
From source file:org.mifosplatform.portfolio.loanaccount.domain.LoanCharge.java
private void populateDerivedFields(final BigDecimal amountPercentageAppliedTo, final BigDecimal chargeAmount, Integer numberOfRepayments, BigDecimal loanCharge) { switch (ChargeCalculationType.fromInt(this.chargeCalculation)) { case INVALID: this.percentage = null; this.amount = null; this.amountPercentageAppliedTo = null; this.amountPaid = null; this.amountOutstanding = BigDecimal.ZERO; this.amountWaived = null; this.amountWrittenOff = null; break;/*w w w. j a v a 2 s .c o m*/ case FLAT: this.percentage = null; this.amountPercentageAppliedTo = null; this.amountPaid = null; if (isInstalmentFee()) { if (numberOfRepayments == null) { numberOfRepayments = this.loan.repaymentScheduleDetail().getNumberOfRepayments(); } this.amount = chargeAmount.multiply(BigDecimal.valueOf(numberOfRepayments)); } else { this.amount = chargeAmount; } this.amountOutstanding = this.amount; this.amountWaived = null; this.amountWrittenOff = null; break; case PERCENT_OF_AMOUNT: case PERCENT_OF_AMOUNT_AND_INTEREST: case PERCENT_OF_INTEREST: this.percentage = chargeAmount; this.amountPercentageAppliedTo = amountPercentageAppliedTo; if (loanCharge.compareTo(BigDecimal.ZERO) == 0) { loanCharge = percentageOf(this.amountPercentageAppliedTo); } this.amount = minimumAndMaximumCap(loanCharge); this.amountPaid = null; this.amountOutstanding = calculateOutstanding(); this.amountWaived = null; this.amountWrittenOff = null; break; } this.amountOrPercentage = chargeAmount; if (this.loan != null && isInstalmentFee()) { /*final Collection<LoanInstallmentCharge> remove = new HashSet<LoanInstallmentCharge>(); final Set<LoanInstallmentCharge> chargePerInstallments = this.loan.generateInstallmentLoanCharges(this); if (this.loanInstallmentCharge.isEmpty()) { this.loanInstallmentCharge.addAll(chargePerInstallments); } else { int index = 0; final LoanInstallmentCharge[] loanChargePerInstallments = new LoanInstallmentCharge[chargePerInstallments.size()]; final LoanInstallmentCharge[] loanChargePerInstallmentArray = chargePerInstallments.toArray(loanChargePerInstallments); for (final LoanInstallmentCharge chargePerInstallment : this.loanInstallmentCharge) { if (index == loanChargePerInstallmentArray.length) { remove.add(chargePerInstallment); chargePerInstallment.updateInstallment(null); } else { chargePerInstallment.copyFrom(loanChargePerInstallmentArray[index++]); } } this.loanInstallmentCharge.removeAll(remove); while (index < loanChargePerInstallmentArray.length - 1) { this.loanInstallmentCharge.add(loanChargePerInstallmentArray[index++]); } }*/ final Set<LoanInstallmentCharge> chargePerInstallments = this.loan.generateInstallmentLoanCharges(this); if (this.loanInstallmentCharge.isEmpty()) { this.loanInstallmentCharge.addAll(chargePerInstallments); } else { int index = 0; final LoanInstallmentCharge[] loanChargePerInstallments = new LoanInstallmentCharge[chargePerInstallments .size()]; final LoanInstallmentCharge[] loanChargePerInstallmentArray = chargePerInstallments .toArray(loanChargePerInstallments); for (final LoanInstallmentCharge chargePerInstallment : this.loanInstallmentCharge) { chargePerInstallment.copyFrom(loanChargePerInstallmentArray[index++]); } } } }
From source file:org.openbravo.costing.AverageCostAdjustment.java
@Override protected void getRelatedTransactionsByAlgorithm() { // Search all transactions after the date of the adjusted line and recalculate the costs of them // to adjust differences MaterialTransaction basetrx = getTransaction(); // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting // the cost of the related opening inventory. if (basetrx.getPhysicalInventoryLine() != null && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) { return;/*from w w w . java 2 s. com*/ } BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum()); Date trxDate = basetrx.getTransactionProcessDate(); BigDecimal adjustmentBalance = BigDecimal.ZERO; BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO; // Initialize adjustment balance looping through all cost adjustment lines of current // transaction. log.debug("Initialize adjustment balance"); CostAdjustmentLine baseCAL = getCostAdjLine(); for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) { if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted() && !costAdjLine.getId().equals(strCostAdjLineId)) { searchRelatedTransactionCosts(costAdjLine); } costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE); if (!costAdjLine.getId().equals(strCostAdjLineId)) { costAdjLine.setParentCostAdjustmentLine(baseCAL); } OBDal.getInstance().save(costAdjLine); // If the cost adjustment line has Transaction Costs those adjustment amount are included // in the Current Value Amount and not in the Adjustment Balance if (!costAdjLine.getTransactionCostList().isEmpty()) { continue; } BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount(); if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) { adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(), getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(), FinancialUtils.PRECISION_STANDARD); } adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier)); if (costAdjLine.isUnitCost()) { unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt); } } // Initialize current stock qty and value amt. BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx, getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed); BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx, getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency()); log.debug( "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}", currentStock.toPlainString(), currentValueAmt.toPlainString()); // Initialize current unit cost including the cost adjustments. Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(), getCostOrg()); if (costing == null) { throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate)); } BigDecimal cost = null; // If current stock is zero the cost is not modified until a related transaction that modifies // the stock is found. if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString()); if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) { BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency()); BigDecimal trxPrice = null; if (basetrx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0 && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection() && AverageAlgorithm.modifiesAverage(trxType)) { // stock was negative and cost different than trx price then Negative Stock Correction // is added BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum()); BigDecimal negCorrAmt = trxPrice.multiply(currentStock) .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt) .subtract(adjustmentBalance); adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null); newCAL.setNegativeStockCorrection(Boolean.TRUE); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); newCAL.setUnitCost(Boolean.FALSE); OBDal.getInstance().save(newCAL); cost = trxPrice; log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(), cost.toPlainString()); } if (basetrx.getMaterialMgmtCostingList().size() == 0) { Date newDate = new Date(); Date dateTo = costing.getEndingDate(); costing.setEndingDate(newDate); OBDal.getInstance().save(costing); Costing newCosting = OBProvider.getInstance().get(Costing.class); newCosting.setCost(cost); newCosting.setCurrency( (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId)); newCosting.setStartingDate(newDate); newCosting.setEndingDate(dateTo); newCosting.setInventoryTransaction(basetrx); newCosting.setProduct(basetrx.getProduct()); if (isManufacturingProduct) { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0")); } else { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId)); } newCosting.setQuantity(basetrx.getMovementQuantity()); newCosting.setTotalMovementQuantity(currentStock); newCosting.setPrice(cost); newCosting.setCostType("AVA"); newCosting.setManual(Boolean.FALSE); newCosting.setPermanent(Boolean.TRUE); newCosting.setProduction(trxType == TrxType.ManufacturingProduced); newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse)); OBDal.getInstance().save(newCosting); OBDal.getInstance().flush(); } else { Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0); if (curCosting.getCost().compareTo(cost) != 0 || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) { curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); // Update existing costing if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setCost(cost); curCosting.setPrice(trxPrice); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().flush(); OBDal.getInstance().save(curCosting); } } } // Modify isManufacturingProduct flag in case it has changed at some point. isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0"); ScrollableResults trxs = getRelatedTransactions(); String strCurrentCurId = strCostCurrencyId; try { while (trxs.next()) { MaterialTransaction trx = (MaterialTransaction) trxs.get()[0]; log.debug("Process related transaction {}", trx.getIdentifier()); BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum()); BigDecimal trxAdjAmt = BigDecimal.ZERO; BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO; if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) { // If there is a backdated source adjustment pending modify the dates of its m_costing. updateBDCostingTimeRange(trx); // This update is done only on the first related transaction. bdCostingId = ""; } if (!strCurrentCurId.equals(trx.getCurrency().getId())) { Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId); Organization costOrg = getCostOrg(); currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency, trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD); if (cost != null) { cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING); } strCurrentCurId = trx.getCurrency().getId(); } List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx); for (CostAdjustmentLine existingCAL : existingAdjLines) { if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) { searchRelatedTransactionCosts(existingCAL); } if (existingCAL.getTransactionCostList().isEmpty() && !existingCAL.isRelatedTransactionAdjusted()) { BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount(); if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) { Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId); adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(), getCostOrg(), FinancialUtils.PRECISION_STANDARD); } trxAdjAmt = trxAdjAmt.add(adjustmentAmt); adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier)); if (existingCAL.isUnitCost()) { trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt); } } existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE); existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance() .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId)); OBDal.getInstance().save(existingCAL); } log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString()); BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false, OBDal.getInstance().get(Currency.class, strCurrentCurId)); BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true, OBDal.getInstance().get(Currency.class, strCurrentCurId)); currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier)); currentStock = currentStock.add(trx.getMovementQuantity()); log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(), currentValueAmt.toPlainString()); TrxType currentTrxType = TrxType.getTrxType(trx); if (AverageAlgorithm.modifiesAverage(currentTrxType)) { // Recalculate average, if current stock is zero the average is not modified if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } if (cost == null) { continue; } log.debug("New average cost: {}", cost.toPlainString()); Costing curCosting = trx.getMaterialMgmtCostingList().get(0); BigDecimal trxPrice = null; if (trx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0 && cost.compareTo(trxPrice) != 0) { // stock was negative and cost different than trx price then Negative Stock Correction // is added BigDecimal negCorrAmt = trxPrice.multiply(currentStock) .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt) .subtract(adjustmentBalance); adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier)); trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null); newCAL.setNegativeStockCorrection(Boolean.TRUE); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); newCAL.setUnitCost(Boolean.FALSE); OBDal.getInstance().save(newCAL); cost = trxPrice; log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(), cost.toPlainString()); } if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId) && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) { // new cost hasn't changed and total movement qty is equal to current stock, following // transactions will have the same cost, so no more // related transactions are needed to include. // If bdCosting is not empty it is needed to loop through the next related transaction // to set the new time ringe of the costing. log.debug("New cost matches existing cost. Adjustment finished."); return; } else { // Update existing costing curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setPrice(trxPrice); curCosting.setCost(cost); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().save(curCosting); } } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) { if (!trx.isCostPermanent()) { // Check current trx unit cost matches new expected cost BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs()) .setScale(stdCurPrecission, RoundingMode.HALF_UP); BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true, OBDal.getInstance().get(Currency.class, strCurrentCurId)); unitCost = unitCost.add(trxAdjAmt); log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(), unitCost.toPlainString()); if (expectedCost.compareTo(unitCost) != 0) { trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier)); trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost)); adjustmentBalance = adjustmentBalance .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier)); // If there is a difference insert a cost adjustment line. CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, expectedCost.subtract(unitCost), null); newCAL.setRelatedTransactionAdjusted(Boolean.TRUE); OBDal.getInstance().save(newCAL); log.debug("Adjustment added. Amount {}.", expectedCost.subtract(unitCost).toPlainString()); } } if (trx.getMaterialMgmtCostingList().size() != 0) { Costing curCosting = trx.getMaterialMgmtCostingList().get(0); if (currentStock.signum() != 0) { cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission, RoundingMode.HALF_UP); } BigDecimal trxPrice = null; if (trx.getMovementQuantity().signum() == 0) { trxPrice = BigDecimal.ZERO; } else { trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(), costCurPrecission, RoundingMode.HALF_UP); } if (curCosting.getCost().compareTo(cost) != 0 || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) { curCosting.setPermanent(Boolean.FALSE); OBDal.getInstance().save(curCosting); OBDal.getInstance().flush(); if (curCosting.getCost().compareTo(cost) != 0) { if (curCosting.getOriginalCost() == null) { curCosting.setOriginalCost(curCosting.getCost()); } curCosting.setPrice(trxPrice); curCosting.setCost(cost); } curCosting.setTotalMovementQuantity(currentStock); curCosting.setPermanent(Boolean.TRUE); OBDal.getInstance().save(curCosting); } } } OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } finally { trxs.close(); } if (getCostingRule().getEndingDate() == null && cost != null) { // This is the current costing rule. Check if current average cost needs to be updated. Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(), getCostDimensions(), getCostOrg()); if (currentCosting == null) { throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(new Date())); } if (currentCosting.getCost().compareTo(cost) != 0) { basetrx = getTransaction(); Date newDate = new Date(); Date dateTo = currentCosting.getEndingDate(); currentCosting.setEndingDate(newDate); OBDal.getInstance().save(currentCosting); Costing newCosting = OBProvider.getInstance().get(Costing.class); newCosting.setCost(cost); newCosting.setCurrency( (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId)); newCosting.setStartingDate(newDate); newCosting.setEndingDate(dateTo); newCosting.setInventoryTransaction(null); newCosting.setProduct(basetrx.getProduct()); if (isManufacturingProduct) { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0")); } else { newCosting.setOrganization( (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId)); } newCosting.setQuantity(null); newCosting.setTotalMovementQuantity(currentStock); newCosting.setPrice(cost); newCosting.setCostType("AVA"); newCosting.setManual(Boolean.FALSE); newCosting.setPermanent(Boolean.TRUE); newCosting.setProduction(trxType == TrxType.ManufacturingProduced); newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse)); OBDal.getInstance().save(newCosting); } } }
From source file:org.libreplan.business.orders.entities.OrderElement.java
/** * Calculates the work hours with the margin {@link Order#getHoursMargin()} for this orderElement. * * @return calculated work hours/*from w ww. jav a2 s .co m*/ */ private EffortDuration calculateWorkHoursWithMargin() { BigDecimal margin = this.getOrder().getHoursMargin() != null ? new BigDecimal(this.getOrder().getHoursMargin()).setScale(2) : BigDecimal.ZERO; BigDecimal hundred = new BigDecimal(100); BigDecimal estimatedHours = new BigDecimal(getWorkHours()).setScale(2); BigDecimal marginHours = estimatedHours.multiply(margin).divide(hundred, 2, BigDecimal.ROUND_HALF_EVEN); BigDecimal result = estimatedHours.add(marginHours); return EffortDuration.fromHoursAsBigDecimal(result); }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;/*from w w w. j av a 2 s . c o m*/ } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = new String(base30StringClean); } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = new String(base30StringNoSign); } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The exponential function.//from w w w.j ava 2 s.co m * * @param x the argument. * @return exp(x). * The precision of the result is implicitly defined by the precision in the argument. * 16 * In particular this means that "Invalid Operation" errors are thrown if catastrophic * cancellation of digits causes the result to have no valid digits left. */ static public BigDecimal exp(BigDecimal x) { /* To calculate the value if x is negative, use exp(-x) = 1/exp(x) */ if (x.compareTo(BigDecimal.ZERO) < 0) { final BigDecimal invx = exp(x.negate()); /* Relative error in inverse of invx is the same as the relative errror in invx. * This is used to define the precision of the result. */ MathContext mc = new MathContext(invx.precision()); return BigDecimal.ONE.divide(invx, mc); } else if (x.compareTo(BigDecimal.ZERO) == 0) { /* recover the valid number of digits from x.ulp(), if x hits the * zero. The x.precision() is 1 then, and does not provide this information. */ return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue()))); } else { /* Push the number in the Taylor expansion down to a small * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order * x^n/n!, and equal to both the absolute and relative error of the result * since the result is close to 1. The x.ulp() sets the relative and absolute error * of the result, as estimated from the first Taylor term. * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp. */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl) { /* Add TAYLOR_NTERM terms of the Taylor expansion (Eulers sum formula) */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifac = BigInteger.ONE; /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right * for each power of 10 in TAYLOR_NTERM, so the addition wont add noise beyond * whats already in x. */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM)); for (int i = 1; i <= TAYLOR_NTERM; i++) { ifac = ifac.multiply(new BigInteger("" + i)); xpowi = xpowi.multiply(x); final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(c); if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) { break; } } /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error * in the result equals the absolute error in the argument. */ MathContext mc = new MathContext(err2prec(xUlpDbl / 2.)); return resul.round(mc); } else { /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead * to loss of accuracy. */ int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0)); BigDecimal xby10 = x.scaleByPowerOfTen(-exSc); BigDecimal expxby10 = exp(xby10); /* Final powering by 10 means that the relative error of the result * is 10 times the relative error of the base (First order binomial expansion). * This looses one digit. */ MathContext mc = new MathContext(expxby10.precision() - exSc); /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation 17 * response by the BigDecimal.pow library or integer overflow. */ while (exSc > 0) { int exsub = Math.min(8, exSc); exSc -= exsub; MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2); int pex = 1; while (exsub-- > 0) { pex *= 10; } expxby10 = expxby10.pow(pex, mctmp); } return expxby10.round(mc); } } }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;// ww w . ja v a2s .c o m } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = base30StringClean; } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = base30StringNoSign; } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } // TODO: Verify that the MathContext/Rounding methods are OK: // -- L.A. 4.0 beta MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }
From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java
private void populateDerivedFields(final BigDecimal amountPercentageAppliedTo, final BigDecimal chargeAmount, Integer numberOfRepayments, BigDecimal loanCharge) { switch (ChargeCalculationType.fromInt(this.chargeCalculation)) { case INVALID: this.percentage = null; this.amount = null; this.amountPercentageAppliedTo = null; this.amountPaid = null; this.amountOutstanding = BigDecimal.ZERO; this.amountWaived = null; this.amountWrittenOff = null; break;//from ww w .j av a2 s . co m case FLAT: this.percentage = null; this.amountPercentageAppliedTo = null; this.amountPaid = null; if (isInstalmentFee()) { if (numberOfRepayments == null) { numberOfRepayments = this.loan.fetchNumberOfInstallmensAfterExceptions(); } this.amount = chargeAmount.multiply(BigDecimal.valueOf(numberOfRepayments)); } else { this.amount = chargeAmount; } this.amountOutstanding = this.amount; this.amountWaived = null; this.amountWrittenOff = null; break; case PERCENT_OF_AMOUNT: case PERCENT_OF_AMOUNT_AND_INTEREST: case PERCENT_OF_INTEREST: case PERCENT_OF_DISBURSEMENT_AMOUNT: this.percentage = chargeAmount; this.amountPercentageAppliedTo = amountPercentageAppliedTo; if (loanCharge.compareTo(BigDecimal.ZERO) == 0) { loanCharge = percentageOf(this.amountPercentageAppliedTo); } this.amount = minimumAndMaximumCap(loanCharge); this.amountPaid = null; this.amountOutstanding = calculateOutstanding(); this.amountWaived = null; this.amountWrittenOff = null; break; } this.amountOrPercentage = chargeAmount; if (this.loan != null && isInstalmentFee()) { updateInstallmentCharges(); } }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) { if (asset == null) return BigDecimal.ZERO; CoinSparkGenesis genesis = asset.getGenesis(); if (genesis == null) return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated. int chargeBasisPoints = genesis.getChargeBasisPoints(); int chargeExponent = genesis.getChargeFlatExponent(); int chargeMantissa = genesis.getChargeFlatMantissa(); int qtyExponent = genesis.getQtyExponent(); int qtyMantissa = genesis.getQtyMantissa(); double interestRate = asset.getInterestRate(); Date issueDate = asset.getIssueDate(); BigDecimal result = new BigDecimal(rawQuantity.toString()); //System.out.println("interest rate = " + interestRate); //System.out.println("issue date = " + issueDate); //System.out.println("raw units =" + result); // 1. Compute interest if (issueDate != null && interestRate != 0.0) { BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); //interestRate = interestRate / 100; //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString()); // get years elapsed DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); //System.out.println("Issue: " + d1 + " Now: " + d2); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString()); // To avoid exception, we need to set a precision. // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.multiply(new BigDecimal(interestMultipler)); //System.out.println("raw units with interest multiplier =" + result); result = result.setScale(0, RoundingMode.DOWN); //System.out.println("raw units with interest multiplier, floored =" + result); }/* w w w.j av a 2 s .c om*/ // 2. Apply multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); BigDecimal display = result; if (decimalPlaces != 0) { // System.out.println(">>>>> display = " + display.toPlainString()); display = result.movePointLeft(decimalPlaces); // System.out.println(">>>>> display = " + display.toPlainString()); } //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent); // double multiple = asset.getMultiple(); // let's just do it for now to make sure code is corret //if (multiple != 1.0) // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // BigDecimal display = result.multiply(m); //System.out.println("multiplier=" + m + ", display=" + display); // Stripping zeros from internal zero with different scale does not work, so use // JDK bug still seems to exist // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539 // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes int cmpZeroResult = display.compareTo(BigDecimal.ZERO); if (decimalPlaces == 0) { display = display.stripTrailingZeros(); } // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead. if (0 == cmpZeroResult) { display = BigDecimal.ZERO; } return display; }