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:Main.java

public static Duration subtract(XMLGregorianCalendar x1, XMLGregorianCalendar x2) {
    boolean positive = x1.compare(x2) >= 0;

    if (!positive) {
        XMLGregorianCalendar temp = x1;
        x1 = x2;/*www .j ava 2 s. co  m*/
        x2 = temp;
    }

    BigDecimal s1 = getSeconds(x1);
    BigDecimal s2 = getSeconds(x2);
    BigDecimal seconds = s1.subtract(s2);
    if (seconds.compareTo(BigDecimal.ZERO) < 0)
        seconds = seconds.add(BigDecimal.valueOf(60));

    GregorianCalendar g1 = x1.toGregorianCalendar();
    GregorianCalendar g2 = x2.toGregorianCalendar();

    int year = 0;
    for (int f : reverseFields) {
        if (f == Calendar.YEAR) {
            int year1 = g1.get(f);
            int year2 = g2.get(f);
            year = year1 - year2;
        } else {
            subtractField(g1, g2, f);
        }
    }

    return FACTORY.newDuration(positive, BigInteger.valueOf(year), BigInteger.valueOf(g1.get(Calendar.MONTH)),
            BigInteger.valueOf(g1.get(Calendar.DAY_OF_MONTH) - 1),
            BigInteger.valueOf(g1.get(Calendar.HOUR_OF_DAY)), BigInteger.valueOf(g1.get(Calendar.MINUTE)),
            seconds);
}

From source file:com.liato.bankdroid.banking.banks.avanza.Avanza.java

public Urllib login() throws LoginException, BankException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_avanza));
    urlopen.addHeader("ctag", "1122334455");
    urlopen.addHeader("Authorization",
            "Basic " + Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.NO_WRAP));

    try {//from   w w w.  j a v a2 s .c o  m
        HttpResponse httpResponse = urlopen.openAsHttpResponse(API_URL + "account/overview/all",
                new ArrayList<NameValuePair>(), false);
        if (httpResponse.getStatusLine().getStatusCode() == 401) {
            throw new LoginException(context.getText(R.string.invalid_username_password).toString());
        }
        ObjectMapper vObjectMapper = new ObjectMapper();
        AccountOverview r = vObjectMapper.readValue(httpResponse.getEntity().getContent(),
                AccountOverview.class);
        for (com.liato.bankdroid.banking.banks.avanza.model.Account account : r.getAccounts()) {
            Account a = new Account(account.getAccountName(), new BigDecimal(account.getOwnCapital()),
                    account.getAccountId());
            if (!account.getCurrencyAccounts().isEmpty()) {
                a.setCurrency(account.getCurrencyAccounts().get(0).getCurrency());
            }
            if (!account.getPositionAggregations().isEmpty()) {
                Date now = new Date();
                ArrayList<Transaction> transactions = new ArrayList<Transaction>();
                for (PositionAggregation positionAgList : account.getPositionAggregations()) {
                    if (positionAgList.getPositions().isEmpty()) {
                        continue;
                    }
                    List<Position> positions = positionAgList.getPositions();
                    transactions.add(new Transaction(Helpers.formatDate(now),
                            "\u2014  " + positionAgList.getInstrumentTypeName() + "  "
                                    + positionAgList.getTotalProfitPercent() + "%  \u2014",
                            BigDecimal.valueOf(positionAgList.getTotalValue()), a.getCurrency()));
                    for (Position p : positions) {
                        Transaction t = new Transaction(Helpers.formatDate(now), p.getInstrumentName(),
                                BigDecimal.valueOf(p.getProfit()), a.getCurrency());
                        transactions.add(t);
                    }
                }
                a.setTransactions(transactions);
            }
            accounts.add(a);
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:org.fineract.module.stellar.TestCreateTrustLine.java

@Test
public void createTrustLineHappyCase() {
    final String secondTenantId = UUID.randomUUID().toString();
    final String secondTenantApiKey = createAndDestroyBridge(secondTenantId, testCleanup,
            testRig.getMifosAddress());/*  www  .j av  a2  s . co m*/
    setVaultSize(secondTenantId, secondTenantApiKey, ASSET_CODE, BigDecimal.TEN);

    final String secondTenantStellarAddress = tenantVaultStellarAddress(secondTenantId);

    createAndDestroyTrustLine(firstTenantId, firstTenantApiKey, secondTenantStellarAddress, ASSET_CODE,
            BigDecimal.valueOf(1000), testCleanup);
}

From source file:info.magnolia.test.mock.jcr.MockValueTest.java

@Test
public void testGetDecimal() throws Exception {
    Object objectValue = BigDecimal.valueOf(123l);
    MockValue jcrValue = new MockValue(objectValue);
    assertEquals(objectValue, jcrValue.getDecimal());
}

From source file:helpers.Methods.java

/**
 * This method converts human readable file size to bytes (1024).
 *
 * @param humanReadableFileSize The human readable file size (Ex. 500MB
 * <b>without space between size and unit</b>)
 * @return the bytes of human readable size in long format.
 *///from www. j  a va2s  .c  o m
public static long filesizeToBytes(String humanReadableFileSize) {
    long returnValue = -1;
    java.util.regex.Pattern patt = java.util.regex.Pattern.compile("([\\d.]+)([GMK]B)",
            java.util.regex.Pattern.CASE_INSENSITIVE);
    Matcher matcher = patt.matcher(humanReadableFileSize);
    Map<String, Integer> powerMap = new HashMap<>();
    powerMap.put("TB", 4);
    powerMap.put("GB", 3);
    powerMap.put("MB", 2);
    powerMap.put("KB", 1);
    powerMap.put("B", 0);
    if (matcher.find()) {
        String number = matcher.group(1);
        int pow = powerMap.get(matcher.group(2).toUpperCase());
        BigDecimal bytes = new BigDecimal(number);
        bytes = bytes.multiply(BigDecimal.valueOf(1024).pow(pow));
        returnValue = bytes.longValue();
    }
    return returnValue;
}

From source file:com.silverpeas.util.MetadataExtractor.java

private void computeMp4Duration(Metadata metadata, MovieHeaderBox movieHeaderBox) {
    BigDecimal duration = BigDecimal.valueOf(movieHeaderBox.getDuration());
    if (duration.intValue() > 0) {
        BigDecimal divisor = BigDecimal.valueOf(movieHeaderBox.getTimescale());

        // Duration
        duration = duration.divide(divisor, 10, BigDecimal.ROUND_HALF_DOWN);
        // get duration in ms
        duration = duration.multiply(BigDecimal.valueOf(1000));
        metadata.add(XMPDM.DURATION, duration.toString());
    }//from  ww w  .ja v a2  s  .co m
}

From source file:fixio.fixprotocol.fields.FieldFactoryTest.java

@Test
public void testValueOfQty() throws Exception {
    BigDecimal value = BigDecimal.valueOf(new Random().nextInt()).movePointLeft(5);

    FloatField field = FieldFactory.valueOf(FieldType.OrderQty.tag(), value.toPlainString().getBytes(US_ASCII));

    assertEquals("tagnum", FieldType.OrderQty.tag(), field.getTagNum());
    assertEquals("value", value.doubleValue(), field.getValue().doubleValue(), 0.0);
    assertEquals("value", value.floatValue(), field.floatValue(), 0.0);
}

From source file:de.hybris.platform.b2bacceleratorservices.jalo.promotions.ProductPriceDiscountPromotionByPaymentType.java

@Override
public List<PromotionResult> evaluate(final SessionContext ctx, final PromotionEvaluationContext promoContext) {
    final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>();
    // Find all valid products in the cart
    final PromotionsManager.RestrictionSetResult restrictionResult = this.findEligibleProductsInBasket(ctx,
            promoContext);//from  w w w . j av  a2 s . c om

    if (restrictionResult.isAllowedToContinue() && !restrictionResult.getAllowedProducts().isEmpty()) {
        final PromotionOrderView view = promoContext.createView(ctx, this,
                restrictionResult.getAllowedProducts());
        final AbstractOrder order = promoContext.getOrder();

        for (final PromotionOrderEntry entry : view.getAllEntries(ctx)) {
            // Get the next order entry
            final long quantityToDiscount = entry.getQuantity(ctx);
            if (quantityToDiscount > 0) {
                final long quantityOfOrderEntry = entry.getBaseOrderEntry().getQuantity(ctx).longValue();

                // The adjustment to the order entry
                final double originalUnitPrice = entry.getBasePrice(ctx).doubleValue();
                final double originalEntryPrice = quantityToDiscount * originalUnitPrice;

                final Currency currency = promoContext.getOrder().getCurrency(ctx);
                Double discountPriceValue;

                final EnumerationValue paymentType = B2BAcceleratorServicesManager.getInstance()
                        .getPaymentType(ctx, order);

                if (paymentType != null
                        && StringUtils.equalsIgnoreCase(paymentType.getCode(), getPaymentType().getCode())) {
                    promoContext.startLoggingConsumed(this);
                    discountPriceValue = this.getPriceForOrder(ctx, this.getProductDiscountPrice(ctx),
                            promoContext.getOrder(),
                            ProductPriceDiscountPromotionByPaymentType.PRODUCTDISCOUNTPRICE);

                    final BigDecimal adjustedEntryPrice = Helper.roundCurrencyValue(ctx, currency,
                            originalEntryPrice - (quantityToDiscount * discountPriceValue.doubleValue()));
                    // Calculate the unit price and round it
                    final BigDecimal adjustedUnitPrice = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.equals(BigDecimal.ZERO) ? BigDecimal.ZERO
                                    : adjustedEntryPrice.divide(BigDecimal.valueOf(quantityToDiscount),
                                            RoundingMode.HALF_EVEN));

                    for (final PromotionOrderEntryConsumed poec : view.consume(ctx, quantityToDiscount)) {
                        poec.setAdjustedUnitPrice(ctx, adjustedUnitPrice.doubleValue());
                    }

                    final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx,
                            this, promoContext.getOrder(), 1.0F);
                    result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, true));
                    final BigDecimal adjustment = Helper.roundCurrencyValue(ctx, currency,
                            adjustedEntryPrice.subtract(BigDecimal.valueOf(originalEntryPrice)));
                    final PromotionOrderEntryAdjustAction poeac = PromotionsManager.getInstance()
                            .createPromotionOrderEntryAdjustAction(ctx, entry.getBaseOrderEntry(),
                                    quantityOfOrderEntry, adjustment.doubleValue());
                    result.addAction(ctx, poeac);
                    promotionResults.add(result);
                }
            }
        }
        final long remainingCount = view.getTotalQuantity(ctx);
        if (remainingCount > 0) {
            promoContext.startLoggingConsumed(this);
            view.consume(ctx, remainingCount);
            final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx, this,
                    promoContext.getOrder(), 0.5F);
            result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, false));
            promotionResults.add(result);
        }
    }
    return promotionResults;
}

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  av  a  2  s .  com*/
    transaction.setTotal(price.multiply(BigDecimal.valueOf(transaction.getQty())));
    return transaction;
}

From source file:com.coinblesk.server.service.UserAccountService.java

@Transactional(readOnly = false)
public Pair<UserAccountStatusTO, UserAccount> createEntity(final UserAccountTO userAccountTO) {
    final String email = userAccountTO.email().toLowerCase(Locale.ENGLISH);
    final UserAccount found = repository.findByEmail(email);
    if (found != null) {
        if (found.getEmailToken() != null) {
            return new Pair<>(
                    new UserAccountStatusTO().type(Type.SUCCESS_BUT_EMAIL_ALREADY_EXISTS_NOT_ACTIVATED), found);
        }//  ww  w  .j a  v a  2s. c  o m
        return new Pair<>(new UserAccountStatusTO().type(Type.SUCCESS_BUT_EMAIL_ALREADY_EXISTS_ACTIVATED),
                found);
    }
    // convert TO to Entity
    UserAccount userAccount = new UserAccount();
    userAccount.setEmail(email);
    userAccount.setPassword(passwordEncoder.encode(userAccountTO.password()));
    userAccount.setCreationDate(new Date());
    userAccount.setDeleted(false);
    userAccount.setEmailToken(UUID.randomUUID().toString());
    userAccount.setUserRole(UserRole.USER);
    userAccount.setBalance(BigDecimal.valueOf(userAccountTO.balance())
            .divide(BigDecimal.valueOf(BitcoinUtils.ONE_BITCOIN_IN_SATOSHI)));
    repository.save(userAccount);
    return new Pair<>(new UserAccountStatusTO().setSuccess(), userAccount);
}