Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose scale is as specified.

Usage

From source file:tasly.greathealth.oms.export.financial.facades.impl.DefaulTaslyFinancialReportFacade.java

private double getPriceByFreight(final double unitPrice, final double sumPrice, final double freight) {
    final BigDecimal unit = new BigDecimal(unitPrice);
    final BigDecimal sum = new BigDecimal(sumPrice);
    final BigDecimal fre = new BigDecimal(freight);

    return unit.divide(sum, 4, BigDecimal.ROUND_HALF_UP).multiply(fre).setScale(2, BigDecimal.ROUND_HALF_UP)
            .doubleValue();// w  ww .  j a v  a  2  s.c  o m
}

From source file:org.libreplan.business.workingday.EffortDuration.java

public BigDecimal toHoursAsDecimalWithScale(int scale) {
    BigDecimal result = BigDecimal.ZERO;
    final BigDecimal secondsPerHour = new BigDecimal(3600);

    for (Entry<Granularity, Integer> each : decompose().entrySet()) {
        BigDecimal seconds = new BigDecimal(each.getKey().toSeconds(each.getValue()));
        result = result.add(seconds.divide(secondsPerHour, scale, BigDecimal.ROUND_HALF_UP));
    }//from  w w  w .j  a  v a 2s  . com
    return result;
}

From source file:com.autentia.tnt.manager.billing.BillManager.java

public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Project project) {

    final List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>();

    ActivityDAO activityDAO = ActivityDAO.getDefault();
    ActivitySearch actSearch = new ActivitySearch();
    actSearch.setBillable(new Boolean(true));
    actSearch.setStartStartDate(start);/*from  ww  w  . ja  v a  2s  .  co  m*/
    actSearch.setEndStartDate(end);

    List<Activity> actividadesTotal = new ArrayList<Activity>();
    Hashtable user_roles = new Hashtable();

    ProjectRoleDAO projectRoleDAO = ProjectRoleDAO.getDefault();
    ProjectRoleSearch prjRolSearch = new ProjectRoleSearch();
    prjRolSearch.setProject(project);
    List<ProjectRole> roles = projectRoleDAO.search(prjRolSearch, new SortCriteria("id", false));
    for (ProjectRole proyRole : roles) {
        actSearch.setRole(proyRole);
        List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false));
        actividadesTotal.addAll(actividades);
    }

    for (Activity act : actividadesTotal) {
        String key = act.getRole().getId().toString() + act.getUser().getId().toString();

        if (!user_roles.containsKey(key)) {
            Hashtable value = new Hashtable();
            value.put("ROLE", act.getRole());
            value.put("USER", act.getUser());
            user_roles.put(key, value);
        }
    }

    Enumeration en = user_roles.keys();

    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        Hashtable pair = (Hashtable) user_roles.get(key);
        actSearch.setBillable(new Boolean(true));
        actSearch.setStartStartDate(start);
        actSearch.setEndStartDate(end);

        ProjectRole pR = (ProjectRole) pair.get("ROLE");
        User u = (User) pair.get("USER");
        actSearch.setRole(pR);
        actSearch.setUser(u);
        List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch,
                new SortCriteria("startDate", false));

        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName());
        brd.setAmount(pR.getCostPerHour());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        BigDecimal unitsTotal = new BigDecimal(0);
        for (Activity act : actividadesUsuarioRol) {
            BigDecimal unitsActual = new BigDecimal(act.getDuration());
            unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
            unitsTotal = unitsTotal.add(unitsActual);
        }
        brd.setUnits(unitsTotal);
        brd.setSelected(true);
        desgloses.add(brd);
    }

    ProjectCostDAO prjCostDAO = ProjectCostDAO.getDefault();
    ProjectCostSearch prjCostSearch = new ProjectCostSearch();
    prjCostSearch.setProject(project);
    List<ProjectCost> costes = prjCostDAO.search(prjCostSearch, new SortCriteria("id", false));
    for (ProjectCost proyCost : costes) {
        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Coste: " + proyCost.getName());
        brd.setUnits(new BigDecimal(1));
        brd.setAmount(proyCost.getCost());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        brd.setSelected(true);
        desgloses.add(brd);
    }

    return desgloses;

}

From source file:se.urvancevav.divider.ListViewFragment.java

private void recalculateSums() {
    BigDecimal total = new BigDecimal(0);
    // Recalculate total sum
    for (int idx = 0; idx < listViewAdapter.getCount(); idx++) {
        ListItem listItem = listViewAdapter.getItem(idx);
        total = total.add(listItem.getPaidAmount());
    }/*  w  w  w  . java  2s.c o  m*/

    BigDecimal meanValue = BigDecimal.ZERO;
    if (!listViewAdapter.isEmpty()) {
        meanValue = total.divide(new BigDecimal(listViewAdapter.getCount()),
                Currency.getInstance(Locale.getDefault()).getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    for (int idx = 0; idx < listViewAdapter.getCount(); idx++) {
        ListItem listItem = listViewAdapter.getItem(idx);
        listItem.setReturnAmount(listItem.getPaidAmount().subtract(meanValue));
    }

    listViewAdapter.notifyDataSetChanged();
}

From source file:org.pentaho.reporting.engine.classic.core.function.ItemAvgFunction.java

/**
 * Returns the function value, in this case the average of all values of a specific column in the report's TableModel.
 *
 * @return The function value.// www .j  a  v  a 2 s. co m
 */
public Object getValue() {
    final BigDecimal count = itemCount.get(lastGroupSequenceNumber);
    if (count == null) {
        return null;
    }
    final BigDecimal sum = this.sum.get(lastGroupSequenceNumber);
    if (sum == null) {
        return null;
    }
    if (count.longValue() == 0) {
        return null;
    }

    return sum.divide(count, scale, roundingMode);
}

From source file:org.openhab.binding.pilight.internal.PilightBinding.java

protected State getState(String value, PilightBindingConfig config) {
    State state = null;/* w  w w  .  j a  v  a 2 s  .  c om*/

    if (config.getItemType().equals(StringItem.class)) {
        state = new StringType(value);
    } else if (config.getItemType().equals(NumberItem.class)) {
        if (!StringUtils.isBlank(value)) {
            // Number values are always received as an integer with an optional parameter describing 
            // the number of decimals (scale, default = 0). 
            BigDecimal numberValue = new BigDecimal(value);
            numberValue = numberValue.divide(new BigDecimal(Math.pow(10, config.getScale())), config.getScale(),
                    RoundingMode.HALF_UP);
            state = new DecimalType(numberValue);
        }
    }

    return state;
}

From source file:org.openvpms.archetype.rules.supplier.OrderGenerator.java

/**
 * Creates a {@link Stock} from {@code set}, if stock needs to be ordered.
 *
 * @param set                the object set
 * @param product            the product
 * @param supplier           the product supplier
 * @param stockLocation      the product stock location
 * @param belowIdealQuantity if {@code true}, create stock if the current quantity {@code <=} the ideal quantity,
 *                           create stock if the current quantity {@code <=} the critical quantity
 * @return the stock, or {@code null} if the requirements for ordering the stock aren't met
 *///from www . ja  v  a  2 s .  c o  m
private Stock getStock(ObjectSet set, Product product, Party supplier, Party stockLocation,
        boolean belowIdealQuantity) {
    Stock stock = null;
    long productSupplierId = set.getLong("productSupplierId");
    BigDecimal quantity = getDecimal("quantity", set);
    BigDecimal idealQty = getDecimal("idealQty", set);
    BigDecimal criticalQty = getDecimal("criticalQty", set);
    int packageSize = set.getInt("packageSize");
    String packageUnits = set.getString("packageUnits");
    String reorderCode = set.getString("reorderCode");
    String reorderDesc = set.getString("reorderDesc");
    BigDecimal nettPrice = getDecimal("nettPrice", set);
    BigDecimal listPrice = getDecimal("listPrice", set);
    BigDecimal orderedQty = getDecimal("orderedQty", set);
    BigDecimal receivedQty = getDecimal("receivedQty", set);
    BigDecimal cancelledQty = getDecimal("cancelledQty", set);
    if (packageSize != 0) {
        BigDecimal decSize = BigDecimal.valueOf(packageSize);
        BigDecimal onOrder;
        if (receivedQty.compareTo(orderedQty) > 0) {
            onOrder = receivedQty;
        } else {
            onOrder = orderedQty.subtract(receivedQty).subtract(cancelledQty);
        }
        BigDecimal current = quantity.add(onOrder); // the on-hand and on-order stock
        BigDecimal toOrder = ZERO;
        BigDecimal units = idealQty.subtract(current); // no. of units required to get to idealQty
        if (!MathRules.equals(ZERO, units)) {
            // Round up as the desired no. may be less than a packageSize, but must order a whole pack.
            toOrder = units.divide(decSize, 0, RoundingMode.UP);
        }

        if (log.isDebugEnabled()) {
            log.debug("Stock: product=" + product.getName() + " (" + product.getId() + "), location="
                    + stockLocation.getName() + " (" + stockLocation.getId() + "), supplier="
                    + supplier.getName() + " (" + supplier.getId() + "), onHand=" + quantity + ", onOrder="
                    + onOrder + ", toOrder=" + toOrder + ", idealQty=" + idealQty + ", criticalQty="
                    + criticalQty);
        }
        if (!MathRules.equals(ZERO, toOrder) && (belowIdealQuantity && current.compareTo(idealQty) <= 0
                || (current.compareTo(criticalQty) <= 0))) {
            stock = new Stock(product, stockLocation, supplier, productSupplierId, quantity, idealQty, onOrder,
                    toOrder, reorderCode, reorderDesc, packageSize, packageUnits, nettPrice, listPrice);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Cannot order product=" + product.getName() + " (" + product.getId() + ") at location="
                    + stockLocation.getName() + " (" + stockLocation.getId() + ") from supplier="
                    + supplier.getName() + " (" + supplier.getId() + ") - no package size");
        }
    }
    return stock;
}

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);
        }//from w ww. ja v  a 2 s .  c  o  m

        // 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.kuali.kfs.module.tem.service.impl.AccountingDistributionServiceImpl.java

@SuppressWarnings("deprecation")
@Override//from www. j  a va  2 s . c  o m
public List<TemSourceAccountingLine> distributionToSouceAccountingLines(
        List<TemDistributionAccountingLine> distributionAccountingLines,
        List<AccountingDistribution> accountingDistributionList, KualiDecimal sourceAccountingLinesTotal,
        KualiDecimal expenseLimit) {
    List<TemSourceAccountingLine> sourceAccountingList = new ArrayList<TemSourceAccountingLine>();
    Map<String, AccountingDistribution> distributionMap = new HashMap<String, AccountingDistribution>();
    KualiDecimal total = KualiDecimal.ZERO;
    int distributionTargetCount = 0;
    boolean useExpenseLimit = false;
    for (AccountingDistribution accountDistribution : accountingDistributionList) {
        if (accountDistribution.getSelected()) {
            total = total.add(accountDistribution.getRemainingAmount());
            distributionTargetCount += 1;
        }
    }

    if (expenseLimit != null && expenseLimit.isPositive()) {
        KualiDecimal expenseLimitTotal = new KualiDecimal(expenseLimit.bigDecimalValue());
        // do we have any accounting line amount to subtract from the expense limit?
        if (sourceAccountingLinesTotal != null && sourceAccountingLinesTotal.isGreaterThan(KualiDecimal.ZERO)) {
            expenseLimitTotal = expenseLimitTotal.subtract(sourceAccountingLinesTotal);
        }
        if (expenseLimitTotal.isLessThan(total)) {
            total = expenseLimitTotal;
            useExpenseLimit = true;
        }
    }

    if (total.isGreaterThan(KualiDecimal.ZERO)) {
        for (AccountingDistribution accountingDistribution : accountingDistributionList) {
            List<TemSourceAccountingLine> tempSourceAccountingList = new ArrayList<TemSourceAccountingLine>();
            if (accountingDistribution.getSelected()) {
                for (TemDistributionAccountingLine accountingLine : distributionAccountingLines) {
                    TemSourceAccountingLine newLine = new TemSourceAccountingLine();
                    try {
                        BeanUtils.copyProperties(newLine, accountingLine);
                    } catch (IllegalAccessException ex) {
                        ex.printStackTrace();
                    } catch (InvocationTargetException ex) {
                        ex.printStackTrace();
                    }
                    BigDecimal distributionAmount = (distributionTargetCount > 1)
                            ? accountingDistribution.getRemainingAmount().bigDecimalValue()
                            : total.bigDecimalValue();
                    BigDecimal product = accountingLine.getAccountLinePercent().multiply(distributionAmount);
                    product = product.divide(new BigDecimal(100), 5, RoundingMode.HALF_UP);
                    BigDecimal lineAmount = product.divide(total.bigDecimalValue(), 5, RoundingMode.HALF_UP);

                    newLine.setAmount(new KualiDecimal(product));
                    newLine.setCardType(accountingDistribution.getCardType());
                    Map<String, Object> fieldValues = new HashMap<String, Object>();
                    fieldValues.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE,
                            accountingDistribution.getObjectCode());
                    fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE,
                            newLine.getChartOfAccountsCode());
                    fieldValues.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR,
                            SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear());
                    ObjectCode objCode = getBusinessObjectService().findByPrimaryKey(ObjectCode.class,
                            fieldValues);
                    newLine.setObjectCode(objCode);
                    newLine.setFinancialObjectCode(accountingDistribution.getObjectCode());
                    tempSourceAccountingList.add(newLine);
                }
                if (useExpenseLimit) {
                    sourceAccountingList.addAll(tempSourceAccountingList); //we just adjusted the accounting lines for the expense...let's not readjust
                } else {
                    sourceAccountingList.addAll(adjustValues(tempSourceAccountingList,
                            accountingDistribution.getRemainingAmount()));
                }
            }
        }
    }
    return sourceAccountingList;
}

From source file:org.sakaiproject.profile2.job.KudosJob.java

/**
 * Gets the score as a percentage, two decimal precision
 * @param score      score for user//from www.  jav  a 2  s  .  c o m
 * @param total      total possible score
 * @return
 */
private BigDecimal getScoreAsPercentage(BigDecimal score, BigDecimal total) {
    return score.divide(total, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).stripTrailingZeros();
}