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:edu.zipcloud.cloudstreetmarket.api.controllers.UsersController.java

private void prepareUserForUpdate(User user) {
    User existingUser = communityService.findOne(user.getId());
    if (!existingUser.getCurrency().equals(user.getCurrency())) {
        CurrencyExchange currencyExchange = currencyExchangeService
                .gather(existingUser.getCurrency().name() + user.getCurrency().name() + "=X");
        BigDecimal change = BigDecimal.valueOf(1L);
        if (currencyExchange != null && currencyExchange.getAsk() != null
                && currencyExchange.getAsk().compareTo(BigDecimal.ZERO) > 0) {
            change = currencyExchange.getAsk();
        }/*from  w w w.ja v a  2  s .c om*/
        //Let's say 2.5% virtual charge applied for now 
        user.setBalance(change.multiply(existingUser.getBalance()).multiply(BigDecimal.valueOf(0.975)));
    } else {
        user.setBalance(existingUser.getBalance());
    }
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.PHS398ModularBudgetV1_1Generator.java

/**
 * //from   ww  w .  j  a v a  2  s .  c  o m
 * This method is used to get Cummulative Budget information from
 * ModularBudget form
 * 
 * @return CummulativeBudgetInfo containing cummulative cost details.
 */
private CummulativeBudgetInfo getCummBudget() {
    CummulativeBudgetInfo cummulativeBudgetInfo = CummulativeBudgetInfo.Factory.newInstance();
    EntirePeriodTotalCost entireCost = EntirePeriodTotalCost.Factory.newInstance();
    // Set default values to mandatory fields
    entireCost.setCumulativeDirectCostLessConsortiumFandA(BigDecimal.ZERO);
    entireCost.setCumulativeTotalFundsRequestedDirectCosts(BigDecimal.ZERO);
    entireCost.setCumulativeTotalFundsRequestedDirectIndirectCosts(BigDecimal.ZERO);

    BudgetJustifications budgetJustifications = BudgetJustifications.Factory.newInstance();
    if (!cumulativeTotalFundsRequestedDirectIndirectCosts.toString().equals("0")) {
        entireCost.setCumulativeDirectCostLessConsortiumFandA(
                cumulativeDirectCostLessConsortiumFandA.bigDecimalValue());
        entireCost.setCumulativeTotalFundsRequestedDirectCosts(
                cumulativeTotalFundsRequestedDirectCosts.bigDecimalValue());
        entireCost.setCumulativeConsortiumFandA(cumulativeConsortiumFandA.bigDecimalValue());
        entireCost.setCumulativeTotalFundsRequestedDirectIndirectCosts(
                cumulativeTotalFundsRequestedDirectIndirectCosts.bigDecimalValue());
        entireCost.setCumulativeTotalFundsRequestedIndirectCost(
                cumulativeTotalFundsRequestedIndirectCost.bigDecimalValue());
        budgetJustifications = getBudgetJustifications();
        if (budgetJustifications.getAdditionalNarrativeJustification() != null
                || budgetJustifications.getConsortiumJustification() != null
                || budgetJustifications.getPersonnelJustification() != null) {
            cummulativeBudgetInfo.setBudgetJustifications(budgetJustifications);
        }
    }
    cummulativeBudgetInfo.setEntirePeriodTotalCost(entireCost);
    return cummulativeBudgetInfo;
}

From source file:com.github.strawberry.guice.config.ConfigLoader.java

/**
 * Utility method to create a default non-null value for the given type
 * parameter. This gets called when {@link Redis#allowNull()} was set to
 * false for the given {@link Field}, and no value for the specified key(s)
 * (see {@link Redis#value()}) was present in the Redis database.
 * @param type The type to create the non-null value for.
 * @return A non-null instance of the type. Note: for primitives this will
 * obviously result in a boxed return value.
 *///from  w w w  .ja va 2s.  com
private static Object nonNullValueOf(Class<?> type) {
    Object value = null;
    if (type.equals(char[].class)) {
        value = new char[] {};
    } else if (type.equals(Character[].class)) {
        value = new Character[] {};
    } else if (type.equals(char.class) || type.equals(Character.class)) {
        value = '\0';
    } else if (type.equals(String.class)) {
        value = "";
    } else if (type.equals(byte[].class)) {
        value = new byte[] {};
    } else if (type.equals(Byte[].class)) {
        value = new Byte[] {};
    } else if (type.equals(byte.class) || type.equals(Byte.class)) {
        value = (byte) 0;
    } else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
        value = false;
    } else if (type.equals(short.class) || type.equals(Short.class)) {
        value = (short) 0;
    } else if (type.equals(int.class) || type.equals(Integer.class)) {
        value = 0;
    } else if (type.equals(long.class) || type.equals(Long.class)) {
        value = 0L;
    } else if (type.equals(BigInteger.class)) {
        value = BigInteger.ZERO;
    } else if (type.equals(float.class) || type.equals(Float.class)) {
        value = 0.0f;
    } else if (type.equals(double.class) || type.equals(Double.class)) {
        value = 0.0;
    } else if (type.equals(BigDecimal.class)) {
        value = BigDecimal.ZERO;
    } else if (Map.class.isAssignableFrom(type)) {
        value = mapImplementationOf(type);
    } else if (Collection.class.isAssignableFrom(type)) {
        value = collectionImplementationOf(type);
    }
    return value;
}

From source file:com.premiumminds.billy.core.services.builders.impl.GenericInvoiceBuilderImpl.java

@Override
@NotOnUpdate/*from  w w  w.  j a va2s  .c  om*/
public TBuilder setSettlementDiscount(BigDecimal discount) {
    Validate.isTrue(discount == null || discount.compareTo(BigDecimal.ZERO) >= 0,
            GenericInvoiceBuilderImpl.LOCALIZER.getString("field.discount")); // TODO
    // message
    this.getTypeInstance().setSettlementDiscount(discount);
    return this.getBuilder();
}

From source file:org.projectforge.statistics.TimesheetDisciplineChartBuilder.java

/**
 * Ein Diagramm, welches ber die letzten n Tage die Tage visualisiert, die zwischen Zeitberichtsdatum und Zeitpunkt der tatschlichen
 * Buchung liegen./*ww  w.j a v a  2s . co m*/
 * @param timesheetDao
 * @param userId
 * @param forLastNDays
 * @param shape e. g. new Ellipse2D.Float(-3, -3, 6, 6) or null, if no marker should be printed.
 * @param stroke e. g. new BasicStroke(3.0f).
 * @param showAxisValues
 * @return
 */
public JFreeChart create(final TimesheetDao timesheetDao, final Integer userId, final short forLastNDays,
        final Shape shape, final Stroke stroke, final boolean showAxisValues) {
    final DayHolder dh = new DayHolder();
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setStopTime(dh.getDate());
    dh.add(Calendar.DATE, -forLastNDays);
    filter.setStartTime(dh.getDate());
    filter.setUserId(userId);
    filter.setOrderType(OrderDirection.ASC);
    final List<TimesheetDO> list = timesheetDao.getList(filter);
    final TimeSeries planSeries = new TimeSeries("Soll");
    final TimeSeries actualSeries = new TimeSeries("Ist");
    final Iterator<TimesheetDO> it = list.iterator();
    TimesheetDO current = null;
    if (it.hasNext() == true) {
        current = it.next();
    }
    long numberOfBookedDays = 0;
    long totalDifference = 0;
    for (int i = 0; i <= forLastNDays; i++) {
        long difference = 0;
        long totalDuration = 0; // Weight for average.
        while (current != null && (dh.isSameDay(current.getStartTime()) == true
                || current.getStartTime().before(dh.getDate()) == true)) {
            long duration = current.getWorkFractionDuration();
            difference += (current.getCreated().getTime() - current.getStartTime().getTime()) * duration;
            totalDuration += duration;
            if (it.hasNext() == true) {
                current = it.next();
            } else {
                current = null;
                break;
            }
        }
        double averageDifference = difference > 0 ? ((double) difference) / totalDuration / 86400000 : 0; // In days.
        final Day day = new Day(dh.getDayOfMonth(), dh.getMonth() + 1, dh.getYear());
        if (averageDifference > 0) {
            planSeries.add(day, PLANNED_AVERAGE_DIFFERENCE_BETWEEN_TIMESHEET_AND_BOOKING); // plan average
            // (PLANNED_AVERAGE_DIFFERENCE_BETWEEN_TIMESHEET_AND_BOOKING
            // days).
            actualSeries.add(day, averageDifference);
            totalDifference += averageDifference;
            numberOfBookedDays++;
        }
        dh.add(Calendar.DATE, 1);
    }
    averageDifferenceBetweenTimesheetAndBooking = numberOfBookedDays > 0 ? new BigDecimal(totalDifference)
            .divide(new BigDecimal(numberOfBookedDays), 1, RoundingMode.HALF_UP) : BigDecimal.ZERO;
    return create(actualSeries, planSeries, shape, stroke, showAxisValues, "days");
}

From source file:com.redhat.rhtracking.core.services.DeliveryMatrixServiceHandler.java

@Override
public Map<String, Object> saveOpportunity(Map<String, Object> event) {
    Map<String, Object> opportunity = new HashMap<>();
    opportunity.put("identifier", (String) event.get("identifier"));
    opportunity.put("project", (String) event.get("project"));
    opportunity.put("opportunityType", (String) event.get("opportunityType"));
    opportunity.put("customerId", (long) event.get("customer"));
    opportunity.put("customerBillingId", (long) event.get("customerBilling"));
    opportunity.put("currency", (String) event.get("currency"));
    opportunity.put("exchangeRate", event.get("exchangeRate"));

    int totalHours = (int) event.get("platformHours") + (int) event.get("middlewareHours")
            + (int) event.get("workshopHours");
    opportunity.put("totalHours", totalHours);
    opportunity.put("hoursToBill", 0);

    BigDecimal billingAmount = ((BigDecimal) event.get("platformPrice"))
            .multiply(new BigDecimal((int) event.get("platformHours")));
    billingAmount = billingAmount.add(((BigDecimal) event.get("middlewarePrice"))
            .multiply(new BigDecimal((int) event.get("middlewareHours"))));
    billingAmount = billingAmount.add(((BigDecimal) event.get("workshopPrice"))
            .multiply(new BigDecimal((int) event.get("workshopHours"))));
    opportunity.put("billingAmount", billingAmount);
    opportunity.put("costAmount", BigDecimal.ZERO);

    Map<String, Object> addOpportunityResponse = opportunityPersistanceService.saveOpportunity(opportunity);
    if (addOpportunityResponse.get("status") != EventStatus.SUCCESS) {
        return addOpportunityResponse;
    }/*ww w.  ja v  a  2s  . c o  m*/

    for (HourType type : HourType.values()) {
        if ((int) event.get(type.toString().toLowerCase() + "Hours") < 1) {
            continue;
        }
        Map<String, Object> newHours = new HashMap<>();
        newHours.put("opportunityId", (long) addOpportunityResponse.get("id"));
        newHours.put("type", type.toString());
        newHours.put("quantity", (int) event.get(type.toString().toLowerCase() + "Hours"));
        newHours.put("hoursToBill", 0);
        newHours.put("unitPrice", event.get(type.toString().toLowerCase() + "Price"));

        Map<String, Object> hourResponse = opportunityPersistanceService.saveOpportunityHours(newHours);
        if (hourResponse.get("status") != com.redhat.rhtracking.events.EventStatus.SUCCESS) {
            throw new UnsupportedOperationException("Exception when creating the opportunity");
        }
    }
    Map<String, Object> result = new HashMap<>();
    result.put("status", com.redhat.rhtracking.events.EventStatus.SUCCESS);
    result.put("id", addOpportunityResponse.get("id"));
    return result;
}

From source file:org.openvpms.component.business.service.archetype.helper.IMObjectBeanTestCase.java

/**
 * Tests the {@link IMObjectBean#getBigDecimal} methods.
 *///from   w ww.j a  va  2s .c  o m
@Test
public void testGetBigDecimal() {
    IMObjectBean bean = createBean("act.types");

    assertNull(bean.getBigDecimal("amount"));
    assertEquals(bean.getBigDecimal("amount", BigDecimal.ZERO), BigDecimal.ZERO);

    BigDecimal expected = new BigDecimal("1234.56");
    bean.setValue("amount", expected);
    assertEquals(expected, bean.getBigDecimal("amount"));

    // quantity has a default value
    assertTrue(BigDecimal.ONE.compareTo(bean.getBigDecimal("quantity")) == 0);
}

From source file:com.axelor.apps.base.service.MapService.java

public HashMap<String, Object> getDirectionMapGoogle(String dString, BigDecimal dLat, BigDecimal dLon,
        String aString, BigDecimal aLat, BigDecimal aLon) {
    LOG.debug("departureString = {}", dString);
    LOG.debug("arrivalString = {}", aString);
    HashMap<String, Object> result = new HashMap<String, Object>();
    try {/*  w ww .jav  a  2s  . com*/
        if (BigDecimal.ZERO.compareTo(dLat) == 0 || BigDecimal.ZERO.compareTo(dLon) == 0) {
            Map<String, Object> googleResponse = geocodeGoogle(dString);
            if (googleResponse != null) {
                dLat = new BigDecimal(googleResponse.get("lat").toString());
                dLon = new BigDecimal(googleResponse.get("lng").toString());
            }
        }
        LOG.debug("departureLat = {}, departureLng={}", dLat, dLon);
        if (BigDecimal.ZERO.compareTo(aLat) == 0 || BigDecimal.ZERO.compareTo(aLon) == 0) {
            Map<String, Object> googleResponse = geocodeGoogle(aString);
            if (googleResponse != null) {
                aLat = new BigDecimal(googleResponse.get("lat").toString());
                aLon = new BigDecimal(googleResponse.get("lng").toString());
            }
        }
        LOG.debug("arrivalLat = {}, arrivalLng={}", aLat, aLon);
        if (BigDecimal.ZERO.compareTo(dLat) != 0 && BigDecimal.ZERO.compareTo(dLon) != 0) {
            if (BigDecimal.ZERO.compareTo(aLat) != 0 && BigDecimal.ZERO.compareTo(aLon) != 0) {
                result.put("url",
                        "map/directions.html?dx=" + dLat + "&dy=" + dLon + "&ax=" + aLat + "&ay=" + aLon);
                result.put("aLat", aLat);
                result.put("dLat", dLat);
                return result;
            }
        }
    } catch (Exception e) {
        TraceBackService.trace(e);
    }

    return null;
}

From source file:net.sourceforge.fenixedu.domain.residence.StudentsPerformanceReport.java

private BigDecimal getA(final Student student) {
    return BigDecimal.ZERO.equals(getEnrolledECTS(student)) ? BigDecimal.ZERO
            : getApprovedECTS(student).divide(getEnrolledECTS(student), 2, RoundingMode.HALF_EVEN);
}

From source file:alfio.util.Validator.java

public static ValidationResult validateAdditionalService(EventModification.AdditionalService additionalService,
        EventModification eventModification, Errors errors) {
    if (additionalService.isFixPrice() && !Optional.ofNullable(additionalService.getPrice())
            .filter(p -> p.compareTo(BigDecimal.ZERO) >= 0).isPresent()) {
        errors.rejectValue("additionalServices", "error.price");
    }/*from   w  w  w  .ja v  a  2 s.  c om*/

    List<EventModification.AdditionalServiceText> descriptions = additionalService.getDescription();
    List<EventModification.AdditionalServiceText> titles = additionalService.getTitle();
    if (descriptions == null || titles == null || titles.size() != descriptions.size()) {
        errors.rejectValue("additionalServices", "error.title");
        errors.rejectValue("additionalServices", "error.description");
    } else {
        if (!validateDescriptionList(titles) || !containsAllRequiredTranslations(eventModification, titles)) {
            errors.rejectValue("additionalServices", "error.title");
        }
        if (!validateDescriptionList(descriptions)
                || !containsAllRequiredTranslations(eventModification, descriptions)) {
            errors.rejectValue("additionalServices", "error.description");
        }
    }

    DateTimeModification inception = additionalService.getInception();
    DateTimeModification expiration = additionalService.getExpiration();
    if (inception == null || expiration == null || expiration.isBefore(inception)) {
        errors.rejectValue("additionalServices", "error.inception");
        errors.rejectValue("additionalServices", "error.expiration");
    } else if (eventModification != null && expiration.isAfter(eventModification.getEnd())) {
        errors.rejectValue("additionalServices", "error.expiration");
    }

    return evaluateValidationResult(errors);

}