Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:ch.algotrader.service.algo.TrailingLimitOrderService.java

private BigDecimal calculateLimit(TrailingLimitOrder algoOrder, BigDecimal last) {

    if (algoOrder.getSide() == Side.BUY) {
        return last.subtract(algoOrder.getTrailingAmount());
    } else {/*from www.  jav  a 2  s  . c o m*/
        return last.add(algoOrder.getTrailingAmount());
    }
}

From source file:com.globalhackv.app.controllers.CitationController.java

@RequestMapping(method = RequestMethod.GET)
public List<CitationViolationResponse> searchCitation(
        @RequestParam(value = "firstName", required = true) String firstName,
        @RequestParam(value = "lastName", required = true) String lastName,
        @RequestParam(value = "dateOfBirth", required = false) String dateOfBirth,
        @RequestParam(value = "driversLicesnse", required = false) String driversLicesnse,
        @RequestParam(value = "citationNumber", required = false) Long citationNumber) {

    List<Citation> citations = new ArrayList<Citation>();

    Citation citation = new Citation();

    citation.setLastName(lastName);// w  w w.  j  a  va  2  s  . c  om
    citation.setFirstName(firstName);
    citation.setDateOfBirth(dateOfBirth);
    citation.setDriversLicense(driversLicesnse);

    if (citationNumber != null) {
        citation.setCitationNumber(citationNumber);
    }

    citations.add(citation);
    List<Citation> citationResults = searchService.findByCitation(citation);

    List<CitationViolationResponse> citationViolations = new ArrayList<CitationViolationResponse>();

    for (Citation cit : citationResults) {
        CitationViolationResponse citationViolationResponse = new CitationViolationResponse();
        List<Violation> violations = searchService.findViolation(cit.getCitationNumber());
        BigDecimal currentTotal = citationViolationResponse.getTotalAmount();
        for (Violation violation : violations) {

            if (violation.getFineAmount() != null) {
                currentTotal = currentTotal.add(violation.getFineAmount());
            }
            if (violation.getCourtCosts() != null) {
                currentTotal = currentTotal.add(violation.getCourtCosts());
            }

            citationViolationResponse.setTotalAmount(currentTotal);

        }
        citationViolationResponse.setCitation(cit);
        citationViolationResponse.setViolations(violations);
        citationViolations.add(citationViolationResponse);
    }

    return citationViolations;
}

From source file:io.seldon.recommendation.VariationTestingClientStrategyTest.java

@Test
public void rangeTest() {
    BigDecimal ratioTotal = new BigDecimal(1.0);
    BigDecimal currentMax = new BigDecimal(0.0);
    BigDecimal r1 = new BigDecimal(0.9);
    BigDecimal r2 = new BigDecimal(0.1);
    NumberRange range1 = new NumberRange(currentMax,
            currentMax.add(r1.divide(ratioTotal, 5, BigDecimal.ROUND_UP)));
    currentMax = currentMax.add(r1);/*  w  w  w . j  a va2s. c  o  m*/
    NumberRange range2 = new NumberRange(currentMax.add(new BigDecimal(0.0001)),
            currentMax.add(r2.divide(ratioTotal, 5, BigDecimal.ROUND_UP)));
    BigDecimal t = new BigDecimal(0.900001);
    Assert.assertTrue(range1.containsNumber(t));
    Assert.assertFalse(range2.containsNumber(t));
    BigDecimal t2 = new BigDecimal(0.901);
    Assert.assertFalse(range1.containsNumber(t2));
    Assert.assertTrue(range2.containsNumber(t2));

}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * generate cosine factor for trigonometric functions in BigDecimal.
 *
 * @param mc {@link java.math.MathContext}.
 * @return list of cosine factors.//  w  ww .  j  a  va  2  s .  co  m
 */
private static List<BigDecimal> initCosineFactor(MathContext mc) {
    int precision = (mc == null ? MathContext.DECIMAL128 : mc).getPrecision();
    List<BigDecimal> factors = new ArrayList<BigDecimal>();
    BigDecimal divisor = BigDecimal.valueOf(2d);
    BigDecimal temporary = BigDecimal.valueOf(2d);
    do {
        factors.add(BigDecimal.ONE.divide(divisor, precision + 2, RoundingMode.HALF_UP));
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
    } while (factors.get(factors.size() - 1).compareTo(new BigDecimal("1E-" + (precision + 2))) > 0);

    return factors;
}

From source file:com.ar.dev.tierra.api.controller.MetodoPagoFacturaController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
@SuppressWarnings("StringEquality")
public ResponseEntity<?> add(OAuth2Authentication authentication, @RequestBody MetodoPagoFactura pagoFactura)
        throws Exception {
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    boolean control = true;
    JsonResponse msg = new JsonResponse();
    @SuppressWarnings("UnusedAssignment")
    NotaCredito notaCredito = null;//w  ww  . j  a v a 2s. c o m
    switch (pagoFactura.getPlanPago().getIdPlanesPago()) {
    case 1:
        PlanPago plan = facadeService.getPlanPagoDAO().searchById(1);
        pagoFactura.setPlanPago(plan);
        break;
    case 4:
        PlanPago planNota = facadeService.getPlanPagoDAO().searchById(2);
        notaCredito = facadeService.getNotaCreditoDAO().getByNumero(pagoFactura.getComprobante());
        if (notaCredito != null) {
            if (pagoFactura.getMontoPago().compareTo(notaCredito.getMontoTotal()) == 0) {
                if (notaCredito.getEstadoUso().equals("SIN USO")) {
                    pagoFactura.setPlanPago(planNota);
                } else if (notaCredito.getEstadoUso().equals("CANCELADO")) {
                    msg = new JsonResponse("Error", "Nota de credito cancelada.");
                    control = false;
                } else {
                    msg = new JsonResponse("Error", "Ya ha sido usada la nota de credito.");
                    control = false;
                }
            } else {
                msg = new JsonResponse("Error", "Monto de la nota de credito invalido.");
                control = false;
            }
        } else {
            msg = new JsonResponse("Error", "Nota de credito invalida.");
            control = false;
        }
    }
    if (control) {
        Factura factura = facadeService.getFacturaDAO().searchById(pagoFactura.getFactura().getIdFactura());
        List<MetodoPagoFactura> list = facadeService.getMetodoPagoFacturaDAO()
                .getFacturaMetodo(factura.getIdFactura());
        /*POSIBLE FALLA, DECIMAL INMUTABLE NO SE SUMAN ENTRE SI, NECESITA TEST*/
        BigDecimal totalFactura = BigDecimal.ZERO;
        for (MetodoPagoFactura metodoPagoFactura : list) {
            totalFactura = totalFactura.add(metodoPagoFactura.getMontoPago());
        }
        if (factura.getTotal().longValue() > totalFactura.longValue()) {
            pagoFactura.setUsuarioCreacion(user.getIdUsuario());
            pagoFactura.setFechaCreacion(new Date());
            pagoFactura.setEstado(true);
            if (notaCredito != null) {
                notaCredito.setFacturaUso(pagoFactura.getFactura().getIdFactura());
                notaCredito.setEstadoUso("USADO");
                facadeService.getNotaCreditoDAO().update(notaCredito);
            }
            facadeService.getMetodoPagoFacturaDAO().add(pagoFactura);
            msg = new JsonResponse("Success", "Metodo de pago agregado con exito");
            return new ResponseEntity<>(msg, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    } else {
        return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
    }
}

From source file:org.mayocat.shop.shipping.DefaultShippingService.java

private ShippingOption getOption(Carrier carrier, Map<Purchasable, Long> items) {
    if (carrier == null) {
        return null;
    }/* w  w w  .  j  a  va  2s.c om*/
    Strategy strategy = carrier.getStrategy();
    try {
        StrategyPriceCalculator priceCalculator = componentManager.getInstance(StrategyPriceCalculator.class,
                carrier.getStrategy().toJson());
        BigDecimal optionPrice = priceCalculator.getPrice(carrier, items);
        BigDecimal vat = optionPrice.multiply(carrier.getVatRate());
        BigDecimal optionPriceIncl = optionPrice.add(vat);

        PriceWithTaxes price = new PriceWithTaxes(optionPriceIncl, optionPrice, carrier.getVatRate());

        return new ShippingOption(carrier.getId(), carrier.getTitle(), price);
    } catch (ComponentLookupException e) {
        throw new RuntimeException("Failed to calculate price for strategy " + strategy.toJson()
                + " : no such strategy calculator");
    }
}

From source file:net.sourceforge.fenixedu.domain.Guide.java

public void updateTotalValue() {

    BigDecimal total = BigDecimal.ZERO;

    for (final GuideEntry guideEntry : getGuideEntriesSet()) {
        total = total
                .add(guideEntry.getPriceBigDecimal().multiply(BigDecimal.valueOf(guideEntry.getQuantity())));
    }/*from   ww  w . j  a  v  a2 s  . c  om*/

    total.setScale(2, RoundingMode.HALF_EVEN);

    setTotalBigDecimal(total);

}

From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java

@Override
public void init(Map<String, Object> params) {
    super.init(params);

    if (securityAssistant.isSuperUser()) {
        timeEntriesDs.setQuery("select e from ts$TimeEntry e "
                + "where e.date >= :component$dateFrom and e.date <= :component$dateTo");
    }/* w w w.j  a v  a 2 s .  com*/

    timeEntriesTable.getColumn("overtime")
            .setAggregation(ComponentsHelper.createAggregationInfo(
                    projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"),
                    new TimeEntryOvertimeAggregation()));

    timeEntriesDs.addCollectionChangeListener(e -> {
        Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create();
        for (TimeEntry item : timeEntriesDs.getItems()) {
            Map<String, Object> key = new TreeMap<>();
            key.put("user", item.getUser());
            key.put("date", item.getDate());
            map.put(key, item);
        }

        for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) {
            BigDecimal thisDaysSummary = BigDecimal.ZERO;
            for (TimeEntry timeEntry : entry.getValue()) {
                thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours());
            }

            for (TimeEntry timeEntry : entry.getValue()) {
                BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate())
                        ? workTimeConfigBean.getWorkHourForDay()
                        : BigDecimal.ZERO;
                BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay);
                timeEntry.setOvertimeInHours(overtime);
            }
        }
    });

    Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1);
    dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH));
    dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1));

    approve.addAction(new AbstractAction("approveAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED);
        }
    });

    approve.addAction(new AbstractAction("approveSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED);
        }
    });

    reject.addAction(new AbstractAction("rejectAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED);
        }
    });

    reject.addAction(new AbstractAction("rejectSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED);
        }
    });

    status.setOptionsList(Arrays.asList(TimeEntryStatus.values()));
    user.setOptionsList(
            projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL));
}

From source file:org.osiam.resource_server.storage.helper.NumberPadder.java

/**
 * Removes the offset and padding from a number
 *
 * @param value//from   ww  w .  j av a 2 s  . co m
 *            the padded number as {@link String}
 * @return the number decreased by offset and leading '0's removed
 */
public String unpad(String value) {
    BigDecimal decimalValue = new BigDecimal(value);
    BigDecimal returnDecimalValue = new BigDecimal(decimalValue.toBigInteger().subtract(BIG_OFFSET));
    BigDecimal signum = new BigDecimal(returnDecimalValue.signum());
    BigDecimal fractionalPart = decimalValue.remainder(BigDecimal.ONE).multiply(signum);
    returnDecimalValue = returnDecimalValue.add(fractionalPart);
    return returnDecimalValue.toString();
}

From source file:com.cubeia.backoffice.accounting.core.entity.Transaction.java

private void ensureEntrySumIsZero(Entry[] entries) throws TransactionNotBalancedException {
    //BigDecimal sum = BigDecimal.ZERO;
    Map<String, BigDecimal> sums = new HashMap<String, BigDecimal>(2);
    for (Entry e : entries) {
        //sum = sum.add(e.getAmount());
        Account a = e.getAccount();//from  w  ww .j  ava 2 s. co  m
        String curr = a.getCurrencyCode();
        BigDecimal sum = sums.get(curr);
        if (sum == null) {
            sum = BigDecimal.ZERO;
        }
        sums.put(curr, sum.add(e.getAmount()));
    }

    for (String curr : sums.keySet()) {
        BigDecimal sum = sums.get(curr);
        if (sum.signum() != 0) {
            throw new TransactionNotBalancedException("Transaction balance is not zero for currency '" + curr
                    + "', sum = " + sum + ". Entries: " + Arrays.toString(entries));
        }
    }
}