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:de.hybris.platform.configurablebundleservices.bundle.impl.FindBundlePricingWithCurrentPriceFactoryStrategyTest.java

@Test
public void testOneTimeChargePriceRuleWinsAgainstPlan() {
    given(childCart.getBillingTime()).willReturn(oneTimeChargeBillingEvent);
    given(priceRule.getBillingEvent()).willReturn(oneTimeChargeBillingEvent);
    given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_LOW_PRICE.doubleValue()));
    given(commercePriceService.getOneTimeChargeEntryPlan(pricePlan, oneTimeChargeBillingEvent))
            .willReturn(oneTimeChargeEntry);
    given(oneTimeChargeEntry.getPrice()).willReturn(ONE_TIME_CHARGE_PLAN_PRICE);
    given(childEntry.getBasePrice()).willReturn(BASE_PRICE);
    given(oneTimeChargeEntry.getId()).willReturn("oneTimeChargeEntry");
    given(priceRule.getId()).willReturn("priceRule");

    final List<DiscountValue> discountValues = Lists.newArrayList();
    bundlePriceFactory.reduceOneTimePrice(pricePlan, priceRule, discountValues, currency, childEntry);

    assertEquals("", 1, discountValues.size());
    final DiscountValue discount = discountValues.iterator().next();
    assertEquals("", "priceRule", discount.getCode());
    assertEquals(BASE_PRICE.doubleValue() - RULE_LOW_PRICE.doubleValue(), discount.getValue(), 0.005);
}

From source file:com.grepcurl.random.BaseGenerator.java

public BigDecimal randomBigDecimal() {
    return BigDecimal.valueOf(randomDouble(DEFAULT_DOUBLE_MIN, DEFAULT_DOUBLE_MAX));
}

From source file:com.opengamma.bloombergexample.loader.ExampleEquityPortfolioLoader.java

/**
 * Create a position of a random number of shares.
 * <p>//from ww  w .j a  v a 2  s  . c  om
 * This creates the position using a random number of units and create one or two trades making up the position.
 *
 * @param security  the security to add a position for, not null
 * @return the position, not null
 */
protected ManageablePosition createPositionAndTrade(EquitySecurity security) {
    s_logger.debug("Creating position {}", security);
    int shares = (RandomUtils.nextInt(490) + 10) * 10;

    ExternalIdBundle bundle = security.getExternalIdBundle(); // we could add an identifier pointing back to the original source database if we're doing an ETL.

    ManageablePosition position = new ManageablePosition(BigDecimal.valueOf(shares), bundle);

    // create random trades that add up in shares to the position they're under (this is not enforced by the system)
    if (shares <= 2000) {
        ManageableTrade trade = new ManageableTrade(BigDecimal.valueOf(shares), bundle,
                LocalDate.of(2010, 12, 3), null, ExternalId.of("CPARTY", "BACS"));
        position.addTrade(trade);
    } else {
        ManageableTrade trade1 = new ManageableTrade(BigDecimal.valueOf(2000), bundle,
                LocalDate.of(2010, 12, 1), null, ExternalId.of("CPARTY", "BACS"));
        position.addTrade(trade1);
        ManageableTrade trade2 = new ManageableTrade(BigDecimal.valueOf(shares - 2000), bundle,
                LocalDate.of(2010, 12, 2), null, ExternalId.of("CPARTY", "BACS"));
        position.addTrade(trade2);
    }
    return position;
}

From source file:org.openbitcoinwidget.WidgetProvider.java

private static String round(Double value, WidgetPreferences preferences) {
    if (value == null) {
        return "N/A";
    }/*  w w  w.j  a  v  a 2s  .  co  m*/
    value *= preferences.getCurrencyUnit().scale;

    int decimals;
    if (value >= 10) {
        decimals = 0;
    } else if (value >= 1) {
        decimals = 1;
    } else if (value >= .1) {
        decimals = 2;
    } else if (value >= .01) {
        decimals = 3;
    } else {
        decimals = 4;
    }

    return BigDecimal.valueOf(value).setScale(decimals, BigDecimal.ROUND_HALF_UP).toString();
}

From source file:it.govpay.model.Versamento.java

public static Causale decode(String encodedCausale) throws UnsupportedEncodingException {
    if (encodedCausale == null || encodedCausale.trim().isEmpty())
        return null;

    String[] causaleSplit = encodedCausale.split(" ");
    if (causaleSplit[0].equals("01")) {
        CausaleSemplice causale = new Versamento().new CausaleSemplice();
        if (causaleSplit.length > 1 && causaleSplit[1] != null) {
            causale.setCausale(new String(Base64.decodeBase64(causaleSplit[1].getBytes()), "UTF-8"));
            return causale;
        } else {/*  w ww. j av  a2 s.  co  m*/
            return null;
        }
    }

    if (causaleSplit[0].equals("02")) {
        List<String> spezzoni = new ArrayList<String>();
        for (int i = 1; i < causaleSplit.length; i++) {
            spezzoni.add(new String(Base64.decodeBase64(causaleSplit[i].getBytes()), "UTF-8"));
        }
        CausaleSpezzoni causale = new Versamento().new CausaleSpezzoni();
        causale.setSpezzoni(spezzoni);
        return causale;
    }

    if (causaleSplit[0].equals("03")) {
        List<String> spezzoni = new ArrayList<String>();
        List<BigDecimal> importi = new ArrayList<BigDecimal>();

        for (int i = 1; i < causaleSplit.length; i = i + 2) {
            spezzoni.add(new String(Base64.decodeBase64(causaleSplit[i].getBytes()), "UTF-8"));
            importi.add(BigDecimal.valueOf(Double
                    .parseDouble(new String(Base64.decodeBase64(causaleSplit[i + 1].getBytes()), "UTF-8"))));
        }
        CausaleSpezzoniStrutturati causale = new Versamento().new CausaleSpezzoniStrutturati();
        causale.setSpezzoni(spezzoni);
        causale.setImporti(importi);
        return causale;
    }
    throw new UnsupportedEncodingException();
}

From source file:Main.java

/**
 * Add two positive Duration objects.//from  w w  w .  j ava  2 s.  co  m
 * @param d1 The first Duration.
 * @param d2 The second Duration.
 * @return The sum of the two durations.
 */
private static Duration addPositiveDurations(Duration d1, Duration d2) {
    BigDecimal s1 = fractionalSeconds(d1);
    BigDecimal s2 = fractionalSeconds(d2);
    BigDecimal extraSeconds = s1.add(s2);

    Duration strip1 = stripFractionalSeconds(d1);
    Duration strip2 = stripFractionalSeconds(d2);

    Duration stripResult = strip1.add(strip2);

    if (extraSeconds.compareTo(BigDecimal.ONE) >= 0) {
        stripResult = stripResult.add(DURATION_1_SECOND);
        extraSeconds = extraSeconds.subtract(BigDecimal.ONE);
    }

    BigDecimal properSeconds = BigDecimal.valueOf(stripResult.getSeconds()).add(extraSeconds);

    return FACTORY.newDuration(true, BigInteger.valueOf(stripResult.getYears()),
            BigInteger.valueOf(stripResult.getMonths()), BigInteger.valueOf(stripResult.getDays()),
            BigInteger.valueOf(stripResult.getHours()), BigInteger.valueOf(stripResult.getMinutes()),
            properSeconds);
}

From source file:com.chinamobile.bcbsp.ml.math.DenseDoubleVector.java

@Override
public double dotUnsafe(DoubleVector vector) {
    BigDecimal dotProduct = BigDecimal.valueOf(0.0d);
    for (int i = 0; i < getLength(); i++) {
        dotProduct = dotProduct// w  w  w . j a va 2 s.c  o  m
                .add(BigDecimal.valueOf(this.get(i)).multiply(BigDecimal.valueOf(vector.get(i))));
    }
    return dotProduct.doubleValue();
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.CommonSourceConfigBean.java

public static BigDecimal getQueriesPerSecondFromInterval(Object queryIntervalValue, int numThreads,
        String queriesPerSecondField, String queryIntervalField) {
    if (numThreads <= 0) {
        LOG.warn("numThreads was given as {} in query rate limit upgrade; switching to default value of 1",
                numThreads);//from  ww  w  . j a  v a2  s . com
        numThreads = 1;
    }

    BigDecimal queriesPerSecond = new BigDecimal(DEFAULT_QUERIES_PER_SECONDS);

    Long intervalSeconds = null;
    if (queryIntervalValue instanceof String) {
        final String queryIntervalExpr = (String) queryIntervalValue;

        // total hack, but we don't have access to a real EL evaluation within upgraders so we will only recognize
        // specific kinds of experssions (namely, the previous default value of ${10 * SECONDS}, or any similar
        // expression with a number other than 10
        final String secondsElExpr = "^\\s*\\$\\{\\s*([0-9]*)\\s*\\*\\s*SECONDS\\s*\\}\\s*$";

        final Matcher matcher = Pattern.compile(secondsElExpr).matcher(queryIntervalExpr);
        if (matcher.matches()) {
            final String secondsStr = matcher.group(1);
            intervalSeconds = Long.valueOf(secondsStr);
        } else if (StringUtils.isNumeric(queryIntervalExpr)) {
            intervalSeconds = Long.valueOf(queryIntervalExpr);
        } else {
            LOG.warn(
                    "{} was a String, but was not a recognized format (either EL expression like '${N * SECONDS}' or simply"
                            + " an integral number, so could not automatically convert it; will use a default value",
                    queryIntervalValue);
        }
    } else if (queryIntervalValue instanceof Integer) {
        intervalSeconds = (long) ((Integer) queryIntervalValue).intValue();
    } else if (queryIntervalValue instanceof Long) {
        intervalSeconds = (Long) queryIntervalValue;
    }

    if (intervalSeconds != null) {
        if (intervalSeconds > 0) {
            // Force a double operation to not lose precision.
            // Don't use BigDecimal#divide() to avoid hitting ArithmeticException if numThreads/intervalSeconds
            // is non-terminating.
            queriesPerSecond = BigDecimal.valueOf(((double) numThreads) / intervalSeconds);
            LOG.info("Calculated a {} value of {} from {} of {} and numThreads of {}", queriesPerSecondField,
                    queriesPerSecond, queryIntervalField, queryIntervalValue, numThreads);
        } else {
            queriesPerSecond = BigDecimal.ZERO;
            LOG.warn(
                    "{} value of {} was not positive, so had to use a value of {} for {}, which means unlimited",
                    queryIntervalField, queryIntervalValue, queriesPerSecondField, queriesPerSecond);
        }
    } else {
        LOG.warn("Could not calculate a {} value, so using a default value of {}", queriesPerSecondField,
                queriesPerSecond);
    }

    return queriesPerSecond;
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that stock is updated when for a charge.
 *
 * @param acts the charge act and item//from ww w . j a v a  2  s.  c om
 */
private void checkStockUpdate(List<FinancialAct> acts) {
    FinancialAct item = acts.get(1);
    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);
    Product product2 = TestHelper.createProduct();

    boolean credit = TypeHelper.isA(item, CustomerAccountArchetypes.CREDIT_ITEM);
    BigDecimal expected = getQuantity(initialQuantity, quantity, credit);

    item.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));

    save(acts);
    checkEquals(expected, getStock(stockLocation, product));

    save(acts); // stock shouldn't change if resaved
    checkEquals(expected, getStock(stockLocation, product));

    item = get(item);
    BigDecimal updatedQty = new BigDecimal(10);
    item.setQuantity(updatedQty);
    expected = getQuantity(initialQuantity, updatedQty, credit);
    save(item);
    checkEquals(expected, getStock(stockLocation, product));

    item = get(item);
    save(item);
    checkEquals(expected, getStock(stockLocation, product));

    ActBean itemBean = new ActBean(item);
    itemBean.setParticipant(ProductArchetypes.PRODUCT_PARTICIPATION, product2);
    save(item);
    checkEquals(BigDecimal.ZERO, getStock(stockLocation, product));
    checkEquals(expected, getStock(stockLocation, product2));
}

From source file:com.app.jdy.ui.CashAdvanceActivity.java

private void addEvents() {
    button.setOnClickListener(new OnClickListener() {

        @Override/*from   w w w .j a v  a  2  s .  c  o m*/
        public void onClick(View v) {

            // ????
            if (HttpUtils.isNetworkConnected(CashAdvanceActivity.this)) {

                if (editText.getText().toString().length() == 0) {
                    Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT).show();
                } else {

                    // ?
                    int count = 0, start = 0;
                    while ((start = editText.getText().toString().indexOf(".", start)) >= 0) {
                        start += ".".length();
                        count++;
                    }
                    if (count > 1 || editText.getText().toString().indexOf(".") == 0) {
                        Toast.makeText(CashAdvanceActivity.this, "", Toast.LENGTH_SHORT)
                                .show();
                    } else {

                        // ?????
                        BigDecimal judgemoney = null;
                        try {
                            judgemoney = new BigDecimal(editText.getText().toString());
                        } catch (NumberFormatException e) {
                            Toast.makeText(CashAdvanceActivity.this, "",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        judgemoney = judgemoney.setScale(2, BigDecimal.ROUND_HALF_UP);

                        // ?????
                        String judgecanWithdCash = textView2.getText().toString();

                        if (textView4.getText().toString().equals("?")
                                || textView4.getText().toString().length() == 0
                                || textView3.getText().toString().length() == 0) {
                            Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (judgemoney.toString() == "0.00") {
                            Toast.makeText(CashAdvanceActivity.this, "?0?",
                                    Toast.LENGTH_SHORT).show();
                        } else if (judgemoney
                                .compareTo(BigDecimal.valueOf(Double.valueOf(judgecanWithdCash))) == 1) {
                            // BigDecimalcompareTo-1 ? 0
                            // 1
                            Toast.makeText(CashAdvanceActivity.this, "??????",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            editText.setText(judgemoney.toString());

                            withdrawCashDialog = new WithdrawCashDialog(CashAdvanceActivity.this,
                                    R.style.ForwardDialog, judgemoney.toString());
                            withdrawCashDialog.show();
                        }

                    }

                }
            } else {
                // ??
                Toast.makeText(CashAdvanceActivity.this, Constants.NO_INTENT_TIPS, Toast.LENGTH_LONG).show();
            }

        }
    });

    // ??????
    findViewById(R.id.cash_textView5).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(CashAdvanceActivity.this, BankCardActivity.class);

            Bundle bundle = new Bundle();
            bundle.putBoolean("isOk", true);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        }
    });

}