Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:org.getwheat.harvest.library.dom.DomHelper.java

/**
 * Converts the value of the specified tag to a BigDecimal.
 * /*from w  ww.j a v  a2  s  .c  om*/
 * @param element the Element to search
 * @param tag the XML Tag to find
 * @return a BigDecimal or null if not found
 */
public BigDecimal getBigDecimalValue(final Element element, final XmlTag tag) {
    BigDecimal value = null;
    final String nodeValue = getStringValue(element, tag);
    if (nodeValue != null) {
        try {
            value = BigDecimal.valueOf(Double.valueOf(nodeValue));
        } catch (Exception ex) {
            LOG.warn("", ex);
        }
    }
    return value;
}

From source file:com.benfante.minimark.po.Assessment.java

@Transient
public BigDecimal getQuestionsTotalWeight() {
    double result = 0;
    for (AssessmentQuestion assessmentQuestion : getQuestions()) {
        final Question question = assessmentQuestion.getQuestion();
        if (question.getWeight() != null) {
            result += question.getWeight().doubleValue();
        }//from  w  w  w . j av a 2  s . c o m
    }
    final BigDecimal bdResult = BigDecimal.valueOf(result);
    bdResult.setScale(2, RoundingMode.HALF_EVEN);
    return bdResult;
}

From source file:com.liato.bankdroid.banking.banks.sebkort.SEBKortBase.java

@Override
public void updateTransactions(Account account, Urllib urlopen) throws LoginException, BankException {
    super.updateTransactions(account, urlopen);
    if (account.getType() != Account.CCARD)
        return;/*from  ww w . ja v  a 2  s.  co m*/
    try {
        PendingTransactionsResponse r = mObjectMapper
                .readValue(
                        urlopen.openStream(String.format("https://%s/nis/m/%s/a/pendingTransactions/%s",
                                mApiBase, mProviderPart, mBillingUnitIds.get(account))),
                        PendingTransactionsResponse.class);
        ArrayList<Transaction> transactions = new ArrayList<Transaction>();
        for (CardGroup cg : r.getBody().getCardGroups()) {
            for (TransactionGroup tg : cg.getTransactionGroups()) {
                for (com.liato.bankdroid.banking.banks.sebkort.model.Transaction t : tg.getTransactions()) {
                    transactions.add(new Transaction(
                            Helpers.formatDate(new Date(t.getOriginalAmountDateDate())), t.getDescription(),
                            BigDecimal.valueOf(t.getAmountNumber()).negate(), account.getCurrency()));
                }
            }
        }
        //TODO: Sort?
        //Collections.sort(transactions, Collections.reverseOrder());
        account.setTransactions(transactions);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:it.av.es.service.impl.OrderServiceHibernate.java

/**
 * {@inheritDoc}/*from w w  w .j a v a2s. c om*/
 */
@Override
public Order forcePriceAndDiscountAndRecalculate(Order o, BigDecimal cost, BigDecimal discountForced) {
    for (ProductOrdered p : o.getProductsOrdered()) {
        p.setAmount(cost.multiply(BigDecimal.valueOf(p.getNumber())));
        p.setDiscount(discountForced.intValue());
    }
    return o;
}

From source file:com.commander4j.util.JUtility.java

public static BigDecimal stringToBigDecimal(String str) {
    BigDecimal result;//  w  w w . java2  s.  c  om

    NumberFormat nf;
    nf = NumberFormat.getNumberInstance(Locale.getDefault());

    try {
        Number myNumber = nf.parse(str);
        Double dbl = myNumber.doubleValue();
        result = BigDecimal.valueOf(dbl);
        str = String.valueOf(dbl);
    } catch (ParseException e) {
        final Logger logger = Logger.getLogger(JUtility.class);
        logger.error(e.getMessage());
        str = "0";
        result = new BigDecimal("0");
    }

    // result = new BigDecimal(str);
    return result;
}

From source file:de.hybris.platform.refund.RefundServiceTest.java

/**
 * Test for BCOM-149//from w ww .jav  a2 s  . co  m
 */
@Test
public void order_calc_when_quantity_equal_0() throws Exception {
    final ProductModel product1 = new ProductModel();
    product1.setCode("test");
    product1.setUnit(productService.getUnit("kg"));
    product1.setCatalogVersion(catalogService.getCatalogVersion("testCatalog", "Online"));
    //product1.setPrice(Double.valueOf(100));

    final PriceRowModel prmodel = modelService.create(PriceRowModel.class);
    prmodel.setCurrency(i18nService.getCurrency("EUR"));
    prmodel.setMinqtd(Long.valueOf(1));
    prmodel.setNet(Boolean.TRUE);
    prmodel.setPrice(Double.valueOf(5.00));
    prmodel.setUnit(productService.getUnit("kg"));
    prmodel.setProduct(product1);
    prmodel.setCatalogVersion(catalogService.getCatalogVersion("testCatalog", "Online"));
    modelService.saveAll(Arrays.asList(prmodel, product1));

    final CartModel cart = cartService.getSessionCart();
    final UserModel user = userService.getCurrentUser();
    cartService.addToCart(cart, product1, 2, null);

    final AddressModel deliveryAddress = new AddressModel();
    deliveryAddress.setOwner(user);
    deliveryAddress.setFirstname("Juergen");
    deliveryAddress.setLastname("Albertsen");
    deliveryAddress.setTown("Muenchen");
    modelService.saveAll(Arrays.asList(deliveryAddress));

    final DebitPaymentInfoModel paymentInfo = new DebitPaymentInfoModel();
    paymentInfo.setOwner(cart);
    paymentInfo.setCode("debit");
    paymentInfo.setBank("MeineBank");
    paymentInfo.setUser(user);
    paymentInfo.setAccountNumber("34434");
    paymentInfo.setBankIDNumber("1111112");
    paymentInfo.setBaOwner("Ich");
    modelService.saveAll(Arrays.asList(paymentInfo));

    // the original order the customer wants to have a refund for
    final OrderModel order = orderService.placeOrder(cart, deliveryAddress, null, paymentInfo);

    // lets create a RMA for it
    final ReturnRequestModel request = returnService.createReturnRequest(order);
    returnService.createRMA(request);

    // based on the original order the call center agent creates a refund order kind of preview (**)
    final OrderModel refundOrderPreview = refundService.createRefundOrderPreview(order);

    // all following "refund processing", will be based on the refund order instance (copy of the original order)
    final AbstractOrderEntryModel productToRefund1 = refundOrderPreview.getEntries().iterator().next(); // has quantity of 2

    // create the preview "refund"
    final RefundEntryModel refundEntry1 = returnService.createRefund(request, productToRefund1, "no.1",
            Long.valueOf(2), ReturnAction.IMMEDIATE, RefundReason.LATEDELIVERY);

    // calculate the preview refund ...
    assertEquals("Unexpected order price!", BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(refundOrderPreview.getTotalPrice().doubleValue()));

    refundService.apply(Arrays.asList(refundEntry1), refundOrderPreview);

    assertEquals("Wrong refund (preview)!", BigDecimal.valueOf(0.0),
            BigDecimal.valueOf(refundOrderPreview.getTotalPrice().doubleValue()));

    assertNull("There shouldn't exists any record entry yet!",
            ((DefaultRefundService) refundService).getModificationHandler().getReturnRecord(order));
    // based on presented "preview" (see **) the customer decides if he wants to accept the offered refund
    // ... and in the case the customer agrees, the call center agent will now recalculate the "original" order
    refundService.apply(refundOrderPreview, request);

    assertEquals("Wrong refund (apply)!", BigDecimal.valueOf(0.0),
            BigDecimal.valueOf(order.getTotalPrice().doubleValue()));

    final Collection<OrderHistoryEntryModel> histories = orderHistoryService.getHistoryEntries(order, null,
            null);

    assertEquals("Wrong count of history entries!", 1, histories.size());

    final OrderHistoryEntryModel history = histories.iterator().next();

    assertEquals("Unexpected orderhistory price!", BigDecimal.valueOf(10.0),
            BigDecimal.valueOf(history.getPreviousOrderVersion().getTotalPrice().doubleValue()));
}

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

/**
 * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Object, java.lang.Number)}.
 *//* w  w  w.jav  a 2 s . com*/
@SuppressWarnings("unchecked")
@Test
public void testAddObjectT() {
    assertEquals("null", null, add((Object) null, null));
    assertEquals("null", null, add("123.456", null));
    assertEquals("null", (Object) 10, add("", 10));
    assertEquals("null", (Object) 10, add((Object) null, 10));
    assertEquals("null", (Object) 123, add("123.456", 0));
    assertEquals("null", (Object) 123.456f, add("123.456d", 0f));
    assertEquals("123 + .456: Float", (Object) 123.456f, add("123", .456f));
    assertEquals("123 + .456: Float", (Object) Float.class, add("123d", .456f).getClass());
    assertEquals("123 + .456: Float", (Object) Float.class,
            add((Object) BigDecimal.valueOf(123d), .456f).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object o = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                o = c.newInstance("123");
            }
            assertEquals("123.456: " + type.getSimpleName(), add(".456", (Number) o, typeOfN),
                    add(".456", (Number) o));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:module.siadap.domain.SiadapEvaluationUniverse.java

private BigDecimal getPonderationResult(BigDecimal scoring, int usedPercentage) {
    BigDecimal percentage = BigDecimal.valueOf(usedPercentage).divide(new BigDecimal(100));

    BigDecimal result = percentage.multiply(scoring);
    return result.setScale(PRECISION, ROUND_MODE);
}

From source file:to.sparks.mtgox.example.TradingBot.java

/**
 * Return the calculated price for the order at the given index in the
 * orders arrays.//w ww  .  ja  va2 s. c  o m
 *
 * @param index The index of the order price/volume in the orders arrays.
 * @return The calulated price of the order at the given index
 */
private static MtGoxFiatCurrency getPriceAtOrderIndex(MtGoxHTTPClient.OrderType orderType,
        MtGoxFiatCurrency lastPrice, int index) {
    MtGoxFiatCurrency price;

    if (orderType == MtGoxHTTPClient.OrderType.Bid) {
        price = new MtGoxFiatCurrency(
                lastPrice.subtract(lastPrice.multiply(BigDecimal.valueOf(percentagesAboveOrBelowPrice[index]))),
                lastPrice.getCurrencyInfo());
    } else {
        price = new MtGoxFiatCurrency(
                lastPrice.add(lastPrice.multiply(BigDecimal.valueOf(percentagesAboveOrBelowPrice[index]))),
                lastPrice.getCurrencyInfo());
    }

    return price;
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from w ww. j a  v a 2 s  . c o m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}