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.mayocat.shop.billing.store.jdbi.mapper.OrderMapper.java

@Override
public Order map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    Order order = new Order();
    fillOrderSummary(resultSet, order);/*from w  ww.j  a v a 2s . co  m*/

    ObjectMapper mapper = new ObjectMapper();
    //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        List<Map<String, Object>> itemsData = mapper.readValue(resultSet.getString("items"),
                new TypeReference<List<Map<String, Object>>>() {
                });

        List<OrderItem> items = FluentIterable.from(itemsData)
                .transform(new Function<Map<String, Object>, OrderItem>() {
                    public OrderItem apply(Map<String, Object> map) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setId(UUID.fromString((String) map.get("id")));
                        orderItem.setOrderId(UUID.fromString((String) map.get("order_id")));
                        if (map.containsKey("purchasable_id") && map.get("purchasable_id") != null) {
                            // There might not be a purchasable id
                            orderItem.setPurchasableId(UUID.fromString((String) map.get("purchasable_id")));
                        }
                        orderItem.setType((String) map.get("type"));
                        orderItem.setTitle((String) map.get("title"));
                        orderItem.setMerchant((String) map.get("merchant"));
                        orderItem.setQuantity(((Integer) map.get("quantity")).longValue());
                        orderItem.setUnitPrice(BigDecimal.valueOf((Double) map.get("unit_price")));
                        orderItem.setItemTotal(BigDecimal.valueOf((Double) map.get("item_total")));
                        if (map.containsKey("vat_rate") && map.get("vat_rate") != null) {
                            // There might not be a VAT rate
                            orderItem.setVatRate(BigDecimal.valueOf((Double) map.get("vat_rate")));
                        }
                        if (map.containsKey("data") && map.get("data") != null) {
                            // There might not be data
                            orderItem.addData((Map<String, Object>) map.get("data"));
                        }
                        return orderItem;
                    }
                }).toList();
        order.setOrderItems(items);
    } catch (IOException e) {
        logger.error("Failed to deserialize order data", e);
    }

    try {
        resultSet.findColumn("email");
        Customer customer = new Customer();
        customer.setId(order.getCustomerId());
        customer.setSlug(resultSet.getString("customer_slug"));
        customer.setEmail(resultSet.getString("email"));
        customer.setFirstName(resultSet.getString("first_name"));
        customer.setLastName(resultSet.getString("last_name"));
        customer.setPhoneNumber(resultSet.getString("phone_number"));
        order.setCustomer(customer);
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("billing_address_id") != null) {
            resultSet.findColumn("billing_address_full_name");
            Address billing = new Address();
            billing.setId((UUID) resultSet.getObject("billing_address_id"));
            billing.setFullName(resultSet.getString("billing_address_full_name"));
            billing.setStreet(resultSet.getString("billing_address_street"));
            billing.setStreetComplement(resultSet.getString("billing_address_street_complement"));
            billing.setZip(resultSet.getString("billing_address_zip"));
            billing.setCity(resultSet.getString("billing_address_city"));
            billing.setCountry(resultSet.getString("billing_address_country"));
            billing.setNote(resultSet.getString("billing_address_note"));
            order.setBillingAddress(billing);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("delivery_address_id") != null) {
            resultSet.findColumn("delivery_address_full_name");
            Address delivery = new Address();
            delivery.setId((UUID) resultSet.getObject("delivery_address_id"));
            delivery.setFullName(resultSet.getString("delivery_address_full_name"));
            delivery.setStreet(resultSet.getString("delivery_address_street"));
            delivery.setStreetComplement(resultSet.getString("delivery_address_street_complement"));
            delivery.setZip(resultSet.getString("delivery_address_zip"));
            delivery.setCity(resultSet.getString("delivery_address_city"));
            delivery.setCountry(resultSet.getString("delivery_address_country"));
            delivery.setNote(resultSet.getString("delivery_address_note"));
            order.setDeliveryAddress(delivery);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    return order;
}

From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testMigration() {
    Product tv = productRepository.findOne(1L);
    assertEquals("TV", tv.getName());
    assertEquals(Long.valueOf(2), tv.getVersion());
    assertEquals(BigDecimal.valueOf(189.99), tv.getPrice());
}

From source file:cz.muni.fi.pv168.airshipmanager.ContractManagerImplTest.java

/**
 * Test of getPrice method, of class ContractManagerImpl.
 *//*  w ww  .jav  a2  s .c o  m*/
@Test
public void testGetPrice() {
    System.out.println("getPrice test run");

    Airship a = new Airship();
    a.setName("Testship");
    a.setPricePerDay(BigDecimal.valueOf(10));

    Contract c1 = new Contract();
    c1.setAirship(a);
    c1.setDiscount(0.85f);
    double expResult = 8.5;
    assertEquals((c1.getDiscount()) * (c1.getAirship().getPricePerDay().doubleValue()), expResult, APPX);
}

From source file:org.impotch.calcul.assurancessociales.CalculCotisationAvsAiApgIndependantTest.java

@Test
public void calculCotisationAvs() {
    assertThat(calculateur2008.calculCotisationAvs(BigDecimal.valueOf(100000))).isEqualTo("7800.00");
}

From source file:com.epam.cme.facades.converters.populator.SearchProductTelcoPopulator.java

@Override
public void populate(final SOURCE source, final TARGET target) {
    final ProductData telcoProduct = target;

    final String billingTimeAsString = this.getValue(source, "billingTime");
    final BillingTimeData billingTime = new BillingTimeData();
    billingTime.setName(billingTimeAsString);

    if (telcoProduct.getSubscriptionTerm() == null) {
        telcoProduct.setSubscriptionTerm(new SubscriptionTermData());
        telcoProduct.getSubscriptionTerm().setBillingPlan(new BillingPlanData());
    }/*  ww w  .j a  v a  2  s  .c om*/

    if (telcoProduct.getSubscriptionTerm().getBillingPlan() == null) {
        telcoProduct.getSubscriptionTerm().setBillingPlan(new BillingPlanData());
    }

    telcoProduct.getSubscriptionTerm().getBillingPlan().setBillingTime(billingTime);

    final Boolean soldIndividually = this.getValue(source, ProductModel.SOLDINDIVIDUALLY);
    telcoProduct.setSoldIndividually(soldIndividually == null ? true : soldIndividually.booleanValue());

    final String termOfServiceFrequencyAsString = this.getValue(source, "termLimit");
    final TermOfServiceFrequencyData termOfServiceFrequencyData = new TermOfServiceFrequencyData();
    termOfServiceFrequencyData.setName(termOfServiceFrequencyAsString);
    telcoProduct.getSubscriptionTerm().setTermOfServiceFrequency(termOfServiceFrequencyData);

    final Double lowestBundlePriceValue = this.getValue(source, "lowestBundlePriceValue");
    telcoProduct.setLowestBundlePrice(lowestBundlePriceValue == null ? null
            : getPriceDataFactory().create(PriceDataType.BUY,
                    BigDecimal.valueOf(lowestBundlePriceValue.doubleValue()),
                    getCommonI18NService().getCurrentCurrency().getIsocode()));
}

From source file:bolt.DucksBoardBolt.java

@Override
public void execute(Tuple tuple) {
    //     System.out.println("INFO: " + tuple.getSourceComponent() + " - " + tuple.getSourceTask());
    // System.out.println(tuple);
    String from = tuple.getSourceComponent();
    int val;

    if (counts.containsKey(from)) {
        val = counts.get(from);
    } else {//from www . j a v a 2  s .co m
        val = 0;
    }

    val++;

    counts.put(from, val);

    totalCount++;

    //     for (String key : counts.keySet()) {
    //        service.pushValue(id, counts.get(key) / totalCount);
    //     }

    if ((totalCount % 10) == 0) {
        double value = (double) counts.get("spout-madrid") / (double) totalCount;
        double value2 = (double) counts.get("spout-barca") / (double) totalCount;
        //     System.out.println("MADRID: " + value);
        //     System.out.println("BARCA: " + value2);
        service.pushValue(id, BigDecimal.valueOf(value));
        service.pushValue(id2, BigDecimal.valueOf(value2));
        service.pushValue(id3, totalCount);
    }
}

From source file:Main.java

/**
 * Compute the natural logarithm of x to a given scale, x > 0.
 *///from  w  ww.j ava2 s.  com
public static BigDecimal ln(BigDecimal x, int scale) {
    // Check that x > 0.
    if (x.signum() <= 0) {
        throw new IllegalArgumentException("x <= 0");
    }

    // The number of digits to the left of the decimal point.
    int magnitude = x.toString().length() - x.scale() - 1;

    if (magnitude < 3) {
        return lnNewton(x, scale);
    }

    // Compute magnitude*ln(x^(1/magnitude)).
    else {

        // x^(1/magnitude)
        BigDecimal root = intRoot(x, magnitude, scale);

        // ln(x^(1/magnitude))
        BigDecimal lnRoot = lnNewton(root, scale);

        // magnitude*ln(x^(1/magnitude))
        return BigDecimal.valueOf(magnitude).multiply(lnRoot).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
    }
}

From source file:com.mitchellbosecke.pebble.spring.PebbleView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.characterEncoding);

    long startNanos = System.nanoTime();

    PebbleTemplate template = this.engine.getTemplate(this.templateName);

    // Add beans context
    model.put(BEANS_VARIABLE_NAME, new Beans(this.getApplicationContext()));

    // Add request & response
    model.put(REQUEST_VARIABLE_NAME, request);
    model.put(RESPONSE_VARIABLE_NAME, response);

    // Add session
    model.put(SESSION_VARIABLE_NAME, request.getSession(false));

    // Locale/*from w  ww .  j a  va 2 s  . co  m*/
    Locale locale = RequestContextUtils.getLocale(request);

    final Writer writer = response.getWriter();
    try {
        template.evaluate(writer, model, locale);
    } finally {
        writer.flush();
    }

    if (TIMER_LOGGER.isDebugEnabled()) {
        long endNanos = System.nanoTime();

        BigDecimal elapsed = BigDecimal.valueOf(endNanos - startNanos);
        BigDecimal elapsedMs = elapsed.divide(BigDecimal.valueOf(NANOS_IN_SECOND), RoundingMode.HALF_UP);
        TIMER_LOGGER.debug("Pebble template \"{}\" with locale {} processed in {} nanoseconds (approx. {}ms)",
                new Object[] { this.templateName, locale, elapsed, elapsedMs });
    }
}

From source file:org.impotch.calcul.assurancessociales.CalculCotisationAvsAiApgIndependantTest.java

@Test
public void calculCotisationAvsAiApg() {
    assertThat(calculateur2008.calculCotisationAvsAiApg(BigDecimal.valueOf(1000)))
            .isEqualByComparingTo("445.00");
    assertThat(calculateur2008.calculCotisationAvsAiApg(BigDecimal.valueOf(100000))).isEqualTo("9500.00");
}

From source file:Main.java

/**
 * convert value to given type.//from  w  w  w  .j av  a 2 s  .  c o  m
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}