Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

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

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:adalid.commons.util.ObjUtils.java

public static BigDecimal sum(Object... objects) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal augend;//from w  ww.j a v  a2 s  .c  o m
    for (Object obj : objects) {
        augend = NumUtils.numberToBigDecimal(obj);
        if (augend == null) {
            return null;
        }
        result.add(augend);
    }
    return result;
}

From source file:com.osafe.services.OsafePayPalServices.java

private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart) throws GenericEntityException {
    encoder.add("CURRENCYCODE", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        encoder.add("L_NUMBER" + line, item.getProductId());
        encoder.add("L_NAME" + line, item.getName());
        encoder.add("L_AMT" + line, item.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;//w ww . j  a v  a2 s . com
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            encoder.add("L_NUMBER" + line, item.getProductId());
            encoder.add("L_NAME" + line, item.getName() + " Adjustments");
            encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            encoder.add("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        encoder.add("L_NUMBER" + line, "N/A");
        encoder.add("L_NAME" + line, "Order Adjustments");
        encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, "1");
        line++;
    }
    encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //encoder.add("SHIPPINGAMT", "0.00");
    //encoder.add("TAXAMT", "0.00");
    encoder.add("SHIPPINGAMT", cart.getTotalShipping().setScale(2).toPlainString());
    encoder.add("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
    encoder.add("AMT", cart.getGrandTotal().setScale(2).toPlainString());
    //encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //NOTE: The docs say this is optional but then won't work without it
    //encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
}

From source file:com.etcc.csc.presentation.datatype.PaymentContext.java

public BigDecimal getFirstInvTotalTollDue() {
    BigDecimal amount = BigDecimal.ZERO;
    if (!ArrayUtils.isEmpty(firstInvs)) {
        for (int i = 0; i < firstInvs.length; i++) {
            if ("N".equals(firstInvs[i].getPaidIndicator())) {
                amount = amount.add(firstInvs[i].getAmount()).subtract(firstInvs[i].getInvoiceAdminFee())
                        .subtract(firstInvs[i].getAdjustedTxnFees())
                        .subtract(firstInvs[i].getInvSecondNoticeAdminFee());
            }/*  w ww. j  ava 2 s  .  c  o m*/
        }
    }
    return amount;
}

From source file:net.sourceforge.fenixedu.domain.credits.util.AnnualTeachingCreditsBean.java

public void calculateCredits() {
    masterDegreeThesesCredits = teacher.getMasterDegreeThesesCredits(executionYear);
    phdDegreeThesesCredits = teacher.getPhdDegreeThesesCredits(executionYear);
    projectsTutorialsCredits = teacher.getProjectsTutorialsCredits(executionYear);

    BigDecimal yearCreditsForFinalCredits = BigDecimal.ZERO;
    BigDecimal annualTeachingLoadFinalCredits = BigDecimal.ZERO;

    boolean hasOrientantionCredits = false;
    boolean hasFinalAndAccumulatedCredits = false;

    for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) {
        if (getTeacher().isActiveForSemester(executionSemester)
                || getTeacher().hasTeacherAuthorization(executionSemester)) {
            BigDecimal thisSemesterManagementFunctionCredits = new BigDecimal(
                    getTeacher().getManagementFunctionsCredits(executionSemester));
            managementFunctionCredits = managementFunctionCredits.add(thisSemesterManagementFunctionCredits);
            serviceExemptionCredits = serviceExemptionCredits
                    .add(new BigDecimal(getTeacher().getServiceExemptionCredits(executionSemester)));
            BigDecimal thisSemesterTeachingLoad = new BigDecimal(
                    getTeacher().getMandatoryLessonHours(executionSemester));
            annualTeachingLoad = annualTeachingLoad.add(thisSemesterTeachingLoad).setScale(2,
                    BigDecimal.ROUND_HALF_UP);
            TeacherService teacherService = getTeacher().getTeacherServiceByExecutionPeriod(executionSemester);
            BigDecimal thisSemesterCreditsReduction = BigDecimal.ZERO;
            if (teacherService != null) {
                teachingCredits = teachingCredits
                        .add(new BigDecimal(teacherService.getTeachingDegreeCredits()));
                thisSemesterCreditsReduction = teacherService.getReductionServiceCredits();
                othersCredits = othersCredits.add(new BigDecimal(teacherService.getOtherServiceCredits()));
            }//from   w w  w . j  av  a  2 s .  co  m
            creditsReduction = creditsReduction.add(thisSemesterCreditsReduction);
            BigDecimal reductionAndManagement = thisSemesterManagementFunctionCredits
                    .add(thisSemesterCreditsReduction);
            BigDecimal thisSemesterYearCredits = thisSemesterTeachingLoad;
            if (thisSemesterTeachingLoad.compareTo(reductionAndManagement) > 0) {
                thisSemesterYearCredits = reductionAndManagement;
            } else {
                setHasAnyLimitation(true);
            }
            yearCredits = yearCredits.add(thisSemesterYearCredits);
            if (getTeacher().isActiveForSemester(executionSemester)
                    && !getTeacher().isMonitor(executionSemester)) {
                yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(thisSemesterYearCredits);
                annualTeachingLoadFinalCredits = annualTeachingLoadFinalCredits.add(thisSemesterTeachingLoad);
                if (executionSemester.getSemester() == 2) {
                    hasFinalAndAccumulatedCredits = true;
                } else {
                    hasOrientantionCredits = true;
                }
            }
        }
    }
    yearCredits = yearCredits.add(teachingCredits).add(serviceExemptionCredits).add(othersCredits);
    yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(teachingCredits).add(serviceExemptionCredits)
            .add(othersCredits);
    if (hasOrientantionCredits) {
        yearCredits = yearCredits.add(getMasterDegreeThesesCredits()).add(getPhdDegreeThesesCredits())
                .add(getProjectsTutorialsCredits()).setScale(2, BigDecimal.ROUND_HALF_UP);
        yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(getMasterDegreeThesesCredits())
                .add(getPhdDegreeThesesCredits()).add(getProjectsTutorialsCredits());
    }
    if (hasFinalAndAccumulatedCredits) {
        finalCredits = yearCreditsForFinalCredits.subtract(annualTeachingLoadFinalCredits);
        BigDecimal lastYearAccumulated = getPreviousAccumulatedCredits();
        accumulatedCredits = (finalCredits.add(lastYearAccumulated)).setScale(2, BigDecimal.ROUND_HALF_UP);
        finalCredits = finalCredits.setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

From source file:mx.edu.um.mateo.inventario.dao.impl.SalidaDaoHibernate.java

@Override
@Transactional(rollbackFor = { NoEstaAbiertaException.class, NoHayExistenciasSuficientes.class,
        NoSePuedeCerrarException.class })
public Salida cierra(Salida salida, Usuario usuario)
        throws NoSePuedeCerrarException, NoHayExistenciasSuficientes, NoEstaAbiertaException {
    if (salida != null) {
        if (salida.getEstatus().getNombre().equals(Constantes.ABIERTA)) {
            if (usuario != null) {
                salida.setAlmacen(usuario.getAlmacen());
            }//from  www.  j a v  a2  s .  c  o  m

            salida.setIva(BigDecimal.ZERO);
            salida.setTotal(BigDecimal.ZERO);
            Date fecha = new Date();
            for (LoteSalida lote : salida.getLotes()) {
                Producto producto = lote.getProducto();
                if (producto.getExistencia().subtract(lote.getCantidad()).compareTo(BigDecimal.ZERO) < 0) {
                    throw new NoHayExistenciasSuficientes(
                            "No existen existencias suficientes de " + producto.getNombre(), producto);
                }
                lote.setPrecioUnitario(producto.getPrecioUnitario());
                currentSession().update(lote);
                producto.setExistencia(producto.getExistencia().subtract(lote.getCantidad()));
                producto.setFechaModificacion(fecha);
                currentSession().update(producto);
                auditaProducto(producto, usuario, Constantes.ACTUALIZAR, salida.getId(), null, fecha);

                BigDecimal subtotal = lote.getPrecioUnitario().multiply(lote.getCantidad());
                salida.setIva(salida.getIva().add(lote.getIva()));
                salida.setTotal(salida.getTotal().add(subtotal.add(lote.getIva())));
            }

            Query query = currentSession().createQuery("select e from Estatus e where e.nombre = :nombre");
            query.setString("nombre", Constantes.CERRADA);
            Estatus estatus = (Estatus) query.uniqueResult();
            salida.setEstatus(estatus);
            salida.setFolio(getFolio(salida.getAlmacen()));
            salida.setAtendio(usuario.getApellido() + ", " + usuario.getNombre());
            salida.setFechaModificacion(fecha);

            currentSession().update(salida);

            audita(salida, usuario, Constantes.ACTUALIZAR, fecha, true);

            currentSession().flush();
            return salida;
        } else {
            throw new NoEstaAbiertaException("No se puede actualizar una salida que no este abierta");
        }
    } else {
        throw new NoSePuedeCerrarException("No se puede cerrar la salida pues no existe");
    }
}

From source file:com.gst.portfolio.savings.domain.SavingsAccountCharge.java

public void update(final BigDecimal amount, final LocalDate dueDate, final MonthDay feeOnMonthDay,
        final Integer feeInterval) {
    final BigDecimal transactionAmount = BigDecimal.ZERO;
    if (dueDate != null) {
        this.dueDate = dueDate.toDate();
        if (isWeeklyFee()) {
            this.feeOnDay = dueDate.getDayOfWeek();
        }/*  ww w.  j  av a  2 s .  c o  m*/
    }

    if (feeOnMonthDay != null) {
        this.feeOnMonth = feeOnMonthDay.getMonthOfYear();
        this.feeOnDay = feeOnMonthDay.getDayOfMonth();
    }

    if (feeInterval != null) {
        this.feeInterval = feeInterval;
    }

    if (amount != null) {
        switch (ChargeCalculationType.fromInt(this.chargeCalculation)) {
        case INVALID:
            break;
        case FLAT:
            this.amount = amount;
            break;
        case PERCENT_OF_AMOUNT:
            this.percentage = amount;
            this.amountPercentageAppliedTo = transactionAmount;
            this.amount = percentageOf(this.amountPercentageAppliedTo, this.percentage);
            this.amountOutstanding = calculateOutstanding();
            break;
        case PERCENT_OF_AMOUNT_AND_INTEREST:
            this.percentage = amount;
            this.amount = null;
            this.amountPercentageAppliedTo = null;
            this.amountOutstanding = null;
            break;
        case PERCENT_OF_INTEREST:
            this.percentage = amount;
            this.amount = null;
            this.amountPercentageAppliedTo = null;
            this.amountOutstanding = null;
            break;
        }
    }
}

From source file:module.siadap.domain.wrappers.SiadapUniverseWrapper.java

public SiadapUniverseWrapper(List<ExceedingQuotaProposal> quotaProposals, String universeDescription,
        SiadapUniverse universeToConsider, UnitSiadapWrapper unitBeingSuggestionsMadeFor,
        boolean quotasUniverse) {

    //a null simple universe and everything else intended for the harmonization purposes
    this.siadapUniverse = null;
    this.excellencyQuota = BigDecimal.ZERO;
    this.relevantQuota = BigDecimal.ZERO;
    this.currentEvaluationExcellents = 0;
    this.currentEvaluationRelevants = 0;
    this.currentHarmonizedExcellents = 0;
    this.currentHarmonizedRelevants = 0;
    this.currentValidatedExcellents = 0;
    this.currentValidatedRelevants = 0;

    this.numberTotalRelevantForQuotaPeopleInUniverse = 0;
    this.globalNumberTotalRelevantForQuotaPeopleInUniverse = 0;

    this.siadapUniverseForSuggestions = new ArrayList<SiadapSuggestionBean>();
    HashSet<SiadapSuggestionBean> siadapUniverseForSuggestionsSet = new HashSet<SiadapSuggestionBean>();
    for (ExceedingQuotaProposal proposal : quotaProposals) {
        siadapUniverseForSuggestions.add(new SiadapSuggestionBean(proposal));
    }/*from   ww w. j  av a 2 s .  c o m*/

    Collections.sort(this.getSiadapUniverseForSuggestions(),
            SiadapSuggestionBean.COMPARATOR_BY_PRIORITY_NUMBER);

    this.siadapUniverseEnum = universeToConsider;

    this.numberRelevantPeopleInUniverse = getSiadapUniverseForSuggestions().size();

    this.universeDescription = universeDescription;

    //no need for the global fields here
    this.globalCurrentEvaluationExcellents = 0;
    this.globalCurrentEvaluationRelevants = 0;
    this.globalCurrentHarmonizedExcellents = 0;
    this.globalCurrentHarmonizedRelevants = 0;
    this.globalCurrentValidatedExcellents = 0;
    this.globalCurrentValidatedRelevants = 0;
    this.globalExcellencyQuota = null;
    this.globalNumberRelevantPeopleInUniverse = 0;
    this.globalRelevantQuota = null;

    this.siadapExceedingQuotaSuggestionsByTypeForUniverse = null;

}

From source file:com.etcc.csc.presentation.datatype.PaymentContext.java

public BigDecimal getFirstInvTotalTXNAdminFee() {
    BigDecimal amount = BigDecimal.ZERO;
    if (!ArrayUtils.isEmpty(firstInvs)) {
        for (int i = 0; i < firstInvs.length; i++) {
            if ("N".equals(firstInvs[i].getPaidIndicator())) {
                amount = amount.add(BigDecimalUtil.nullSafe(firstInvs[i].getAdjustedTxnFees()));
            }/*  ww w.  j a  va  2  s  .co m*/
        }
    }
    return amount;
}

From source file:org.devgateway.ocds.web.rest.controller.CorruptionRiskDashboardIndicatorsStatsController.java

@ApiOperation(value = "Percent of eligible projects flagged (denominator is number of eligible projects)")
@RequestMapping(value = "/api/percentOfEligibleProjectsFlaggedByYear", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> percentOfEligibleProjectsFlaggedByYear(final YearFilterPagingRequest filter) {

    //get the total projects eligible by year
    List<DBObject> totalFlaggedProjects = totalFlaggedProjectsByIndicatorTypeByYear(filter);

    //denominator total projects eligible by year
    List<DBObject> totalEligibleProjectsByYear = totalEligibleProjectsByIndicatorTypeByYear(filter);

    //because this is reversed, we may end up with empty percentages on the eligible side, so we need to add zeros
    totalEligibleProjectsByYear.forEach(e -> {
        e.put(Keys.PERCENT, BigDecimal.ZERO);
        e.put(Keys.FLAGGED_PROJECT_COUNT, 0);
    });/* w w  w  .ja va2  s.  c  o m*/

    totalEligibleProjectsByYear.forEach(e -> {
        findByYearAndTypeAndMonth(totalFlaggedProjects, (Integer) e.get(Keys.YEAR), (String) e.get(Keys.TYPE),
                (Integer) e.get(Keys.MONTH)).forEach(f -> {
                    e.put(Keys.FLAGGED_PROJECT_COUNT, f.get(Keys.FLAGGED_PROJECT_COUNT));
                    e.put(Keys.PERCENT,
                            (BigDecimal.valueOf((Integer) f.get(Keys.FLAGGED_PROJECT_COUNT))
                                    .setScale(BIGDECIMAL_SCALE)
                                    .divide(BigDecimal.valueOf((Integer) e.get(Keys.ELIGIBLE_PROJECT_COUNT)),
                                            BigDecimal.ROUND_HALF_UP)
                                    .multiply(ONE_HUNDRED)));
                });
    });

    return totalEligibleProjectsByYear;
}

From source file:org.devgateway.ocds.web.rest.controller.CostEffectivenessVisualsController.java

@ApiOperation(value = "Aggregated version of /api/costEffectivenessTenderAmount and "
        + "/api/costEffectivenessAwardAmount."
        + "This endpoint aggregates the responses from the specified endpoints, per year. "
        + "Responds to the same filters.")
@RequestMapping(value = "/api/costEffectivenessTenderAwardAmount", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> costEffectivenessTenderAwardAmount(
        @ModelAttribute @Valid final GroupingFilterPagingRequest filter) {

    Future<List<DBObject>> costEffectivenessAwardAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override//from  w w w .ja va2  s . c  om
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessAwardAmount(filter);
                }
            }, filter);

    Future<List<DBObject>> costEffectivenessTenderAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessTenderAmount(filter);
                }
            }, filter);

    //this is completely unnecessary since the #get methods are blocking
    //controllerLookupService.waitTillDone(costEffectivenessAwardAmountFuture, costEffectivenessTenderAmountFuture);

    LinkedHashMap<Object, DBObject> response = new LinkedHashMap<>();

    try {

        costEffectivenessAwardAmountFuture.get()
                .forEach(dbobj -> response.put(getYearMonthlyKey(filter, dbobj), dbobj));
        costEffectivenessTenderAmountFuture.get().forEach(dbobj -> {
            if (response.containsKey(getYearMonthlyKey(filter, dbobj))) {
                Map<?, ?> map = dbobj.toMap();
                map.remove(Keys.YEAR);
                if (filter.getMonthly()) {
                    map.remove(Keys.MONTH);
                }
                response.get(getYearMonthlyKey(filter, dbobj)).putAll(map);
            } else {
                response.put(getYearMonthlyKey(filter, dbobj), dbobj);
            }
        });

    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }

    Collection<DBObject> respCollection = response.values();

    respCollection.forEach(dbobj -> {

        BigDecimal totalTenderAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue());

        BigDecimal totalAwardAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue());

        dbobj.put(Keys.DIFF_TENDER_AWARD_AMOUNT, totalTenderAmount.subtract(totalAwardAmount));

        dbobj.put(Keys.PERCENTAGE_AWARD_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (totalAwardAmount.setScale(15).divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP)
                                .multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

        dbobj.put(Keys.PERCENTAGE_DIFF_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (((BigDecimal) dbobj.get(Keys.DIFF_TENDER_AWARD_AMOUNT)).setScale(15)
                                .divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP).multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

    });

    return new ArrayList<>(respCollection);
}