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:com.coinblesk.client.utils.UIUtils.java

public static Coin getValue(Context context, String amount) {
    BigDecimal bdAmount = new BigDecimal(amount);
    BigDecimal multiplicand = new BigDecimal(Coin.COIN.getValue());

    if (SharedPrefUtils.isBitcoinScaleBTC(context)) {
        multiplicand = new BigDecimal(Coin.COIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) {
        multiplicand = new BigDecimal((Coin.MILLICOIN.getValue()));
    } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) {
        multiplicand = new BigDecimal((Coin.MICROCOIN.getValue()));
    }//  ww w .  j  a v a  2s .c o  m
    return Coin.valueOf((bdAmount.multiply(multiplicand).longValue()));
}

From source file:id.ac.ipb.ilkom.training.controller.OrderController.java

@RequestMapping(value = "/add-to-cart", method = RequestMethod.POST)
@ResponseBody//w  ww.  j  av  a2 s .c o m
public AddToCartResponse addToCart(Integer productId, Integer quantity, HttpSession session) {
    //check if user already login or not
    Customer customer = (Customer) session.getAttribute("customer");
    if (customer == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Please login before buy product.");
        return response;
    }
    //check product
    Product product = productService.getProduct(productId);
    if (product == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Product id " + productId + " is not found .");
        return response;
    }
    Order order = (Order) session.getAttribute("cart");
    if (order == null) {
        List<OrderItem> orderItems = new ArrayList<>();
        order = new Order();
        order.setOrderItems(orderItems);
    }
    boolean isProductFoundInOrderItems = false;
    for (OrderItem orderItem : order.getOrderItems()) {
        if (orderItem.getProduct().getId().equals(productId)) {
            orderItem.setQuantity(orderItem.getQuantity() + quantity);
            isProductFoundInOrderItems = true;
            break;
        }
    }
    if (!isProductFoundInOrderItems) {
        OrderItem orderItem = new OrderItem();
        orderItem.setQuantity(quantity);
        orderItem.setProduct(product);
        orderItem.setPrice(product.getPrice());
        orderItem.setOrder(order); //tambahan
        order.getOrderItems().add(orderItem);
    }
    BigDecimal total = BigDecimal.ZERO;
    for (OrderItem orderItem : order.getOrderItems()) {
        BigDecimal price = orderItem.getPrice();
        BigDecimal subTotal = price.multiply(new BigDecimal(orderItem.getQuantity()));
        total = total.add(subTotal);
    }
    order.setCreatedDate(new Date());
    order.setCustomer(customer);
    order.setTotal(total);
    //check
    session.setAttribute("cart", order);
    AddToCartResponse response = new AddToCartResponse();
    response.setResult(true);
    return response;
}

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

public static BigDecimal cos(final BigDecimal angle, MathContext mc, boolean isRadians) {
    if (angle == null)
        return null;
    BigDecimal cos = BigDecimal.ONE;
    BigDecimal radians = isRadians ? angle : valueOf(toRadians(angle), BigDecimal.class);
    BigDecimal nSquare = radians.pow(2);
    int index = 0;
    for (BigDecimal factor : COSINE_FACTOR_DECIMAL128) {
        BigDecimal temporary = factor.multiply(nSquare);
        if (index % 2 == 0)
            temporary = temporary.negate();
        cos = cos.add(temporary);/*from w w w .  j  a v  a 2 s .c o  m*/
        nSquare = nSquare.multiply(radians.pow(2)).setScale(
                ((mc == null ? MathContext.DECIMAL128 : mc).getPrecision() + 2), RoundingMode.HALF_UP);
        index++;
    }

    return cos.setScale((mc == null ? MathContext.DECIMAL128 : mc).getPrecision(), RoundingMode.HALF_UP);
}

From source file:com.gtp.tradeapp.rest.TransactionController.java

private Transaction updateWithLatestPrice(Transaction transaction) {
    MarketInstrument latestStockPrice = dataService.getLatestStockPrice(transaction.getTicker());
    BigDecimal price = latestStockPrice.getStocklist().get(0).getPrice();

    transaction.setPrice(price);/*from w  ww  .  j a  v a  2  s.  c o  m*/
    transaction.setTotal(price.multiply(BigDecimal.valueOf(transaction.getQty())));
    return transaction;
}

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

private ShippingOption getOption(Carrier carrier, Map<Purchasable, Long> items) {
    if (carrier == null) {
        return null;
    }/*from w w w. j  a v  a  2 s.c o m*/
    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:org.gradle.performance.measure.DataSeries.java

public DataSeries(Iterable<? extends Amount<Q>> values) {
    for (Amount<Q> value : values) {
        if (value != null) {
            add(value);//  w w w. j a va  2 s  .c  om
        }
    }

    if (isEmpty()) {
        average = null;
        median = null;
        max = null;
        min = null;
        standardError = null;
        return;
    }

    Amount<Q> total = get(0);
    Amount<Q> min = get(0);
    Amount<Q> max = get(0);
    for (int i = 1; i < size(); i++) {
        Amount<Q> amount = get(i);
        total = total.plus(amount);
        min = min.compareTo(amount) <= 0 ? min : amount;
        max = max.compareTo(amount) >= 0 ? max : amount;
    }
    List<Amount<Q>> sorted = Lists.newArrayList(this);
    Collections.sort(sorted);
    Amount<Q> medianLeft = sorted.get((sorted.size() - 1) / 2);
    Amount<Q> medianRight = sorted.get((sorted.size() - 1) / 2 + 1 - sorted.size() % 2);
    median = medianLeft.plus(medianRight).div(2);
    average = total.div(size());
    this.min = min;
    this.max = max;

    BigDecimal sumSquares = BigDecimal.ZERO;
    Units<Q> baseUnits = average.getUnits().getBaseUnits();
    BigDecimal averageValue = average.toUnits(baseUnits).getValue();
    for (int i = 0; i < size(); i++) {
        Amount<Q> amount = get(i);
        BigDecimal diff = amount.toUnits(baseUnits).getValue();
        diff = diff.subtract(averageValue);
        diff = diff.multiply(diff);
        sumSquares = sumSquares.add(diff);
    }
    // This isn't quite right, as we may lose precision when converting to a double
    BigDecimal result = BigDecimal
            .valueOf(Math
                    .sqrt(sumSquares.divide(BigDecimal.valueOf(size()), RoundingMode.HALF_UP).doubleValue()))
            .setScale(2, RoundingMode.HALF_UP);

    standardError = Amount.valueOf(result, baseUnits);
}

From source file:org.gradle.api.internal.tasks.testing.junit.report.DefaultTestReport.java

private void mergeFromFile(File file, AllTestResults model) {
    try {/*from   ww w . j  a v  a 2  s. c o m*/
        InputStream inputStream = new FileInputStream(file);
        Document document;
        try {
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new InputSource(inputStream));
        } finally {
            inputStream.close();
        }
        NodeList testCases = document.getElementsByTagName("testcase");
        for (int i = 0; i < testCases.getLength(); i++) {
            Element testCase = (Element) testCases.item(i);
            String className = testCase.getAttribute("classname");
            String testName = testCase.getAttribute("name");
            LocaleSafeDecimalFormat format = new LocaleSafeDecimalFormat();
            BigDecimal duration = format.parse(testCase.getAttribute("time"));
            duration = duration.multiply(BigDecimal.valueOf(1000));
            NodeList failures = testCase.getElementsByTagName("failure");
            TestResult testResult = model.addTest(className, testName, duration.longValue());
            for (int j = 0; j < failures.getLength(); j++) {
                Element failure = (Element) failures.item(j);
                testResult.addFailure(failure.getAttribute("message"), failure.getTextContent());
            }
        }
        NodeList ignoredTestCases = document.getElementsByTagName("ignored-testcase");
        for (int i = 0; i < ignoredTestCases.getLength(); i++) {
            Element testCase = (Element) ignoredTestCases.item(i);
            String className = testCase.getAttribute("classname");
            String testName = testCase.getAttribute("name");
            model.addTest(className, testName, 0).ignored();
        }
        String suiteClassName = document.getDocumentElement().getAttribute("name");
        ClassTestResults suiteResults = model.addTestClass(suiteClassName);
        NodeList stdOutElements = document.getElementsByTagName("system-out");
        for (int i = 0; i < stdOutElements.getLength(); i++) {
            suiteResults.addStandardOutput(stdOutElements.item(i).getTextContent());
        }
        NodeList stdErrElements = document.getElementsByTagName("system-err");
        for (int i = 0; i < stdErrElements.getLength(); i++) {
            suiteResults.addStandardError(stdErrElements.item(i).getTextContent());
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not load test results from '%s'.", file), e);
    }
}

From source file:com.ning.billing.invoice.dao.InvoiceItemDaoTests.java

@Test
public void testGetInvoiceItemsByInvoiceId() {
    UUID invoiceId = UUID.randomUUID();
    DateTime startDate = new DateTime(2011, 3, 1, 0, 0, 0, 0);
    BigDecimal rate = new BigDecimal("20.00");

    for (int i = 0; i < 5; i++) {
        UUID subscriptionId = UUID.randomUUID();
        BigDecimal amount = rate.multiply(new BigDecimal(i + 1));
        DefaultInvoiceItem item = new DefaultInvoiceItem(invoiceId, subscriptionId, startDate,
                startDate.plusMonths(1), "test", amount, amount, Currency.USD);
        invoiceItemDao.create(item);/* www  .jav a 2  s .co  m*/
    }

    List<InvoiceItem> items = invoiceItemDao.getInvoiceItemsByInvoice(invoiceId.toString());
    assertEquals(items.size(), 5);
}

From source file:ca.travelagency.salesstats.InvoiceSales.java

public BigDecimal getCommissionEstimated() {
    if (systemUser == null) {
        return MoneyUtils.ZERO_VALUE;
    }//from w  w w. ja  v a 2 s .  c o  m
    BigDecimal commission = getTotalSales().getCommission();
    BigDecimal commissionRate = new BigDecimal(systemUser.getCommissionRate() / 100);
    return MoneyUtils.round(commission.multiply(commissionRate));
}

From source file:ca.travelagency.salesstats.InvoiceSales.java

public BigDecimal getCommissionRPayable() {
    if (systemUser == null) {
        return MoneyUtils.ZERO_VALUE;
    }/* ww w. j a v  a2s. c  om*/
    BigDecimal commissionReceived = getTotalSales().getCommissionReceived();
    BigDecimal commissionRate = new BigDecimal(systemUser.getCommissionRate() / 100);
    return MoneyUtils.round(commissionReceived.multiply(commissionRate));
}