Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:org.micromanager.plugins.magellan.autofocus.CrossCorrelationAutofocus.java

/**
 * Called by acquisitions at then end of time point
 * @param timeIndex //w  w w.  j ava 2s.  co  m
  */
public void run(int timeIndex) throws Exception {
    Log.log("________", true);
    Log.log("Autofocus for acq " + acq_.getName() + "  Time point " + timeIndex, true);
    if (timeIndex == 0) {
        //get initial position
        try {
            currentPosition_ = initialPosition_;
            previousPosition_ = initialPosition_;
        } catch (Exception e) {
            Log.log("Couldn't get autofocus Z drive initial position", true);
        }
        //figure out which resolution level will be used for xCorr
        MultiResMultipageTiffStorage storage = acq_.getStorage();
        //do these calulations with BigIntegers to prevent overflow and Nan values
        BigInteger tileWidth = new BigInteger(storage.getTileWidth() + "");
        BigInteger tileHeight = new BigInteger(storage.getTileHeight() + "");
        BigInteger numCols = new BigInteger(acq_.getNumColumns() + "");
        BigInteger numRows = new BigInteger(acq_.getNumRows() + "");
        //figure out how much downsampling needed to run autofocus in a reasonable amount of time
        //factor of two is for z padding
        BigDecimal numPix2D = new BigDecimal(
                tileWidth.multiply(numCols).multiply(tileHeight).multiply(numRows));
        BigDecimal numXCorrSlices = new BigDecimal((acq_.getNumSlices()) + "");
        double dsFactor = //ratio of number of voxels to voxel target
                Math.sqrt(numPix2D.multiply(numXCorrSlices)
                        .divide(new BigDecimal((double) NUM_VOXEL_TARGET), RoundingMode.UP).doubleValue());
        downsampleIndex_ = (int) Math.max(0, Math.round(Math.log(dsFactor) / Math.log(2)));
        downsampledWidth_ = (int) (tileWidth.multiply(numCols).longValue() / Math.pow(2, downsampleIndex_));
        downsampledHeight_ = (int) (tileHeight.multiply(numRows).longValue() / Math.pow(2, downsampleIndex_));
        Log.log("Drift compensation DS Index: " + downsampleIndex_, false);
        Log.log("Drift compensation DS Width: " + downsampledWidth_, false);
        Log.log("Drift compensation DS Height: " + downsampledHeight_, false);
    } else {
        ImageStack lastTPStack = createAFStack(acq_, timeIndex - 1, channelIndex_, downsampledWidth_,
                downsampledHeight_, downsampleIndex_);
        ImageStack currentTPStack = createAFStack(acq_, timeIndex, channelIndex_, downsampledWidth_,
                downsampledHeight_, downsampleIndex_);
        //run autofocus
        //image drift is the difference between this TP and the previous one
        //but does not represent the acutal drift because these 2 TPs will likely have different 
        //positions for the AF compensation Z device
        //drifteCorrection = move for the AF drive to bring current TP to position of previous TP
        double driftCorrection = -calcFocusDrift(acq_.getName(), lastTPStack, currentTPStack, acq_.getZStep());
        Log.log(acq_.getName() + " Drift compensation: correction = " + driftCorrection, true);
        //now add in a factor accounting for the previous AF
        //i.e. how far the reference image is from the desired position
        driftCorrection += (currentPosition_ - previousPosition_);
        Log.log(acq_.getName() + " Drift compensation: correction (accounting for previous position) = "
                + driftCorrection, true);

        //check if outside max displacement
        if (Math.abs(currentPosition_ + driftCorrection - initialPosition_) > maxDisplacement_) {
            Log.log("Calculated focus drift of " + driftCorrection
                    + " um exceeds tolerance. Leaving autofocus offset unchanged", true);
            return;
        }
        Log.log("New position: " + (currentPosition_ + driftCorrection), true);
        previousPosition_ = currentPosition_;
        currentPosition_ += driftCorrection;
    }
}

From source file:org.egov.ptis.repository.dashboard.RevenueDashboardRepository.java

public Map<String, Object> collectionsPaymentMode() {
    final List<Object[]> typeCollection = getQuery("revenue.ptis.collecion.payment.type").list();
    final BigDecimal totalTransactions = BigDecimal
            .valueOf((Double) getQuery("revenue.ptis.collecion.total").uniqueResult());
    final DecimalFormat df = new DecimalFormat("####0.00");
    final List<Map<String, Object>> overAllCollHolder = new LinkedList<Map<String, Object>>();
    final Map<String, BigDecimal> overallCollPercHolder = new HashMap<String, BigDecimal>();
    for (final Object[] collObj : typeCollection) {
        final Map<String, Object> collPaymentType = new HashMap<String, Object>();
        collPaymentType.put("name", String.valueOf(collObj[0]));
        BigDecimal collectionPerc = collObj[1] != null ? new BigDecimal(collObj[1].toString())
                : BigDecimal.ZERO;
        collectionPerc = collectionPerc.multiply(BigDecimal.valueOf(100)).divide(totalTransactions, 2,
                RoundingMode.HALF_UP);
        overallCollPercHolder.put(String.valueOf(collObj[0]),
                collectionPerc != null ? collectionPerc : BigDecimal.ZERO);
        collPaymentType.put("y",
                collectionPerc != null ? new BigDecimal(df.format(collectionPerc.doubleValue())) : 0);
        overAllCollHolder.add(collPaymentType);
    }// www . ja va  2  s  .  co  m

    final List<Object[]> totalNoTransactions = getQuery("revenue.ptis.collecion.total.type").list();
    final List<Map<String, Object>> totalPercTrans = new LinkedList<Map<String, Object>>();
    final BigDecimal totalCount = new BigDecimal(
            getQuery("revenue.ptis.collecion.total.count").uniqueResult().toString());
    for (final Object[] revenueObj : totalNoTransactions) {
        final Map<String, Object> revnTotalTransData = new HashMap<String, Object>();
        revnTotalTransData.put("name", String.valueOf(revenueObj[0]));
        BigDecimal numberTransactions = revenueObj[1] != null ? new BigDecimal(revenueObj[1].toString())
                : BigDecimal.ZERO;
        numberTransactions = numberTransactions.multiply(BigDecimal.valueOf(100)).divide(totalCount, 2,
                RoundingMode.HALF_UP);
        revnTotalTransData.put("y",
                numberTransactions != null ? new BigDecimal(df.format(numberTransactions.doubleValue())) : 0);
        revnTotalTransData.put("overAllPerc", new BigDecimal(
                df.format(overallCollPercHolder.get(String.valueOf(revenueObj[0])).doubleValue())));
        totalPercTrans.add(revnTotalTransData);
    }
    // SORT BY TOTAL COUNT %
    sortData(totalPercTrans, "y");

    // SORT BY COLLECTION %
    sortData(overAllCollHolder, "y");

    // SORT BACK BY OVER ALL COUNT %
    sortData(totalPercTrans, "overAllPerc");

    final Map<String, Object> revenueAggrData = new HashMap<String, Object>();
    revenueAggrData.put("overallColl", overAllCollHolder);
    revenueAggrData.put("totalTransPerc", totalPercTrans);

    return revenueAggrData;
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.AccruedLeaveBalance.java

@Override
public void remove(LeaveBlock leaveBlock) throws MaximumBalanceException, NegativeBalanceException {

    if (leaveBlock.getLeaveLocalDate().compareTo(asOfDate) <= 0) {

        try {/*w ww .j  a  v a 2  s . com*/
            ytdUsage.remove(leaveBlock);
        } catch (NegativeBalanceException e1) {
            e1.printStackTrace();
        }

        ytdEarned.remove(leaveBlock);

        try {
            carryOver.remove(leaveBlock);
        } catch (MaxCarryoverException e) {
            e.printStackTrace();
        }

        AccrualCategoryRule accrualRule = getAccrualCategoryRuleForDate(leaveBlock.getLeaveLocalDate());
        EarnCodeContract earnCode = HrServiceLocator.getEarnCodeService().getEarnCode(leaveBlock.getEarnCode(),
                leaveBlock.getLeaveLocalDate());
        if (earnCode != null) {
            if (earnCode.getAccrualBalanceAction().equals(HrConstants.ACCRUAL_BALANCE_ACTION.USAGE)) {
                //validate and add to / subtract from balances
                if (leaveBlock.getLeaveAmount().signum() < 0) {
                    //removing a negative amount
                    if (accrualRule != null && StringUtils.isNotEmpty(accrualRule.getMaxBalFlag())
                            && StringUtils.equals(accrualRule.getMaxBalFlag(), "Y")) {

                        BigDecimal maxBalance = accrualRule.getMaxBalance();
                        BigDecimal fteSum = HrServiceLocator.getJobService()
                                .getFteSumForAllActiveLeaveEligibleJobs(leaveBlock.getPrincipalId(),
                                        leaveBlock.getLeaveLocalDate());
                        maxBalance = maxBalance.multiply(fteSum).setScale(HrConstants.BIG_DECIMAL_SCALE,
                                HrConstants.BIG_DECIMAL_SCALE_ROUNDING);

                        EmployeeOverrideContract employeeOverride = getEmployeeOverride(leaveBlock, "MB");
                        if (employeeOverride != null)
                            maxBalance = new BigDecimal(employeeOverride.getOverrideValue());

                        if (maxBalance.compareTo(this.balance.subtract(leaveBlock.getLeaveAmount())) <= 0) {
                            remove(leaveBlock.getLeaveAmount());
                            leaveBlocks.remove(leaveBlock);
                            //throw new MaximumBalanceException();
                        } else {
                            remove(leaveBlock.getLeaveAmount());
                            leaveBlocks.remove(leaveBlock);
                        }
                    } else {
                        remove(leaveBlock.getLeaveAmount());
                        leaveBlocks.remove(leaveBlock);
                    }
                } else {
                    //removing a positive amount
                    if (StringUtils.equals(earnCode.getAllowNegativeAccrualBalance(), "N")) {
                        if (BigDecimal.ZERO
                                .compareTo(this.balance.subtract(leaveBlock.getLeaveAmount())) <= 0) {
                            remove(leaveBlock.getLeaveAmount());
                            leaveBlocks.remove(leaveBlock);
                        } else {
                            remove(leaveBlock.getLeaveAmount());
                            leaveBlocks.remove(leaveBlock);
                            //throw new NegativeBalanceException();
                        }
                    } else {
                        remove(leaveBlock.getLeaveAmount());
                        leaveBlocks.remove(leaveBlock);
                    }
                }
            } else if (earnCode.getAccrualBalanceAction()
                    .equals(HrConstants.ACCRUAL_BALANCE_ACTION.ADJUSTMENT)) {
                //does not validate against balances
                remove(leaveBlock.getLeaveAmount());
                leaveBlocks.remove(leaveBlock);
            } else if (earnCode.getAccrualBalanceAction().equals(HrConstants.ACCRUAL_BALANCE_ACTION.NONE)) {
                //no balance validations, does not affect balances
                leaveBlocks.remove(leaveBlock);
            }

        }
        //this balance should equal carryOver + ytdEarned.balance - ytdUsage.balance
    }
}

From source file:co.nubetech.apache.hadoop.TextSplitter.java

/**
 * Return a BigDecimal representation of string 'str' suitable for use in a
 * numerically-sorting order.//  w w  w  . j  ava  2s.  c om
 */
BigDecimal stringToBigDecimal(String str) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal curPlace = ONE_PLACE; // start with 1/65536 to compute the
    // first digit.

    int len = Math.min(str.length(), MAX_CHARS);

    for (int i = 0; i < len; i++) {
        int codePoint = str.codePointAt(i);
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(65536^2) for
        // the second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.AccruedLeaveBalance.java

@Override
public void add(LeaveBlock leaveBlock) throws MaximumBalanceException, NegativeBalanceException {
    //TODO: Is the leave block within the previous calendar year ( carryover ), a current calendar year ( could be planned/future usage ), or 
    // a future calendar year ( is planned/future if usage; no balance action if accrual. )
    //DateTime prevRolloverDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(principalCalendar.getLeavePlan(), asOfDate);
    if (leaveBlock.getLeaveLocalDate().compareTo(asOfDate) <= 0) {

        try {// w  ww. j ava 2  s .c o m
            ytdUsage.add(leaveBlock);
        } catch (UsageLimitException e) {
            e.printStackTrace();
        }

        ytdEarned.add(leaveBlock);

        try {
            carryOver.add(leaveBlock);
        } catch (MaxCarryoverException e) {
            e.printStackTrace();
        }

        EarnCodeContract earnCode = HrServiceLocator.getEarnCodeService().getEarnCode(leaveBlock.getEarnCode(),
                leaveBlock.getLeaveLocalDate());
        if (earnCode != null) {
            if (earnCode.getAccrualBalanceAction().equals(HrConstants.ACCRUAL_BALANCE_ACTION.USAGE)) {

                AccrualCategoryRule accrualRule = getAccrualCategoryRuleForDate(leaveBlock.getLeaveLocalDate());

                if (leaveBlock.getLeaveAmount().signum() < 0) {
                    if (StringUtils.equals(earnCode.getAllowNegativeAccrualBalance(), "N")) {
                        if (BigDecimal.ZERO.compareTo(leaveBlock.getLeaveAmount().add(this.balance)) <= 0) {
                            add(leaveBlock.getLeaveAmount());
                            leaveBlocks.add(leaveBlock);
                        } else if (StringUtils.equals(earnCode.getAllowNegativeAccrualBalance(), "Y")) {
                            add(leaveBlock.getLeaveAmount());
                            leaveBlocks.add(leaveBlock);
                        } else {
                            add(leaveBlock.getLeaveAmount());
                            leaveBlocks.add(leaveBlock);
                            //throw new NegativeBalanceException();
                        }
                    } else {
                        add(leaveBlock.getLeaveAmount());
                        leaveBlocks.add(leaveBlock);
                    }
                } else {
                    if (accrualRule != null && StringUtils.isNotEmpty(accrualRule.getMaxBalFlag())
                            && StringUtils.equals(accrualRule.getMaxBalFlag(), "Y")) {

                        BigDecimal maxBalance = accrualRule.getMaxBalance();
                        BigDecimal fteSum = HrServiceLocator.getJobService()
                                .getFteSumForAllActiveLeaveEligibleJobs(leaveBlock.getPrincipalId(),
                                        leaveBlock.getLeaveLocalDate());
                        maxBalance = maxBalance.multiply(fteSum).setScale(HrConstants.BIG_DECIMAL_SCALE,
                                HrConstants.BIG_DECIMAL_SCALE_ROUNDING);

                        EmployeeOverrideContract employeeOverride = getEmployeeOverride(leaveBlock, "MB");
                        if (employeeOverride != null)
                            maxBalance = new BigDecimal(employeeOverride.getOverrideValue());

                        if (maxBalance.compareTo(leaveBlock.getLeaveAmount().add(this.balance)) <= 0) {
                            add(leaveBlock.getLeaveAmount());
                            leaveBlocks.add(leaveBlock);
                        } else {
                            add(leaveBlock.getLeaveAmount());
                            leaveBlocks.add(leaveBlock);
                            //throw new MaximumBalanceException();
                        }
                    } else {
                        add(leaveBlock.getLeaveAmount());
                        leaveBlocks.add(leaveBlock);
                    }
                }
            } else if (earnCode.getAccrualBalanceAction()
                    .equals(HrConstants.ACCRUAL_BALANCE_ACTION.ADJUSTMENT)) {
                //does not validate against balances
                add(leaveBlock.getLeaveAmount());

                leaveBlocks.add(leaveBlock);
            } else if (earnCode.getAccrualBalanceAction().equals(HrConstants.ACCRUAL_BALANCE_ACTION.NONE)) {
                //no balance validations, does not affect balances
                leaveBlocks.add(leaveBlock);
            }

        }
    }
    //this balance should equal carryOver + ytdEarned.balance - ytdUsage.balance 
}

From source file:net.groupbuy.controller.admin.ProductController.java

/**
 * /*from   w w w  .j  a v a2s .  c  o  m*/
 * 
 * @param price
 *            
 */
private long calculateDefaultPoint(BigDecimal price) {
    Setting setting = SettingUtils.get();
    Double defaultPointScale = setting.getDefaultPointScale();
    return price.multiply(new BigDecimal(defaultPointScale.toString())).longValue();
}

From source file:org.libreplan.business.qualityforms.entities.QualityForm.java

private void updatePercentageByItems() {
    if (qualityFormItems.size() > 0) {
        BigDecimal percentageTotal = new BigDecimal(100).setScale(2);
        BigDecimal numItems = new BigDecimal(qualityFormItems.size()).setScale(2);
        BigDecimal percentageByItem = percentageTotal.divide(numItems, 2, BigDecimal.ROUND_DOWN);
        for (QualityFormItem item : qualityFormItems) {
            item.setPercentage(percentageByItem);
        }//  w w  w  .  j  a  va  2  s .  c om

        // Calculate the division remainder
        BigDecimal sumByItems = (percentageByItem.multiply(numItems)).setScale(2);
        BigDecimal remainder = (percentageTotal.subtract(sumByItems)).setScale(2);
        QualityFormItem lastItem = qualityFormItems.get(qualityFormItems.size() - 1);
        BigDecimal lastPercentage = (lastItem.getPercentage().add(remainder)).setScale(2);
        lastItem.setPercentage(lastPercentage);
    }
}

From source file:org.finra.dm.dao.helper.EmrPricingHelper.java

/**
 * Returns the total cost per hour to run the requested number of instances for the given price. Returns the instance price multiplied by the number of
 * instances.//from   w  w  w  .  ja  v  a2 s .com
 *
 * @param ec2Price The EC2 pricing information
 *
 * @return USD per hour
 */
public BigDecimal getTotalCost(Ec2PriceDto ec2Price) {
    BigDecimal instancePrice = ec2Price.getInstancePrice();
    Integer instanceCount = ec2Price.getInstanceCount();
    return instancePrice.multiply(new BigDecimal(instanceCount));
}

From source file:net.groupbuy.plugin.PaymentPlugin.java

/**
 * /*from  ww w  . j a v  a  2 s .co  m*/
 * 
 * @param amount
 *            ?
 * @return 
 */
public BigDecimal calculateFee(BigDecimal amount) {
    Setting setting = SettingUtils.get();
    BigDecimal fee;
    if (getFeeType() == FeeType.scale) {
        fee = amount.multiply(getFee());
    } else {
        fee = getFee();
    }
    return setting.setScale(fee);
}

From source file:net.groupbuy.controller.admin.ProductController.java

/**
 * /* w  ww. j a v a2s. c o  m*/
 * 
 * @param price
 *            
 */
private BigDecimal calculateDefaultMarketPrice(BigDecimal price) {
    Setting setting = SettingUtils.get();
    Double defaultMarketPriceScale = setting.getDefaultMarketPriceScale();
    return setting.setScale(price.multiply(new BigDecimal(defaultMarketPriceScale.toString())));
}