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:com.streamsets.pipeline.stage.it.DecimalTypeIT.java

@Test
public void correctCases() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12.12)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);//  w  w w  .  j a  v  a  2 s.  c o  m

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("dec", Field.create(BigDecimal.valueOf(1.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 3));
    map.put("dec", Field.create(BigDecimal.valueOf(12.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 4));
    map.put("dec", Field.create(BigDecimal.valueOf(0.1)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 5));
    map.put("dec", Field.create(BigDecimal.valueOf(0.12)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12.12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(3, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(4, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(5, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.12), rs.getBigDecimal(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:io.coala.time.Rate.java

/**
 * {@link Rate} constructor for "natural" polymorphic Jackson bean
 * deserialization//from  w w  w  .ja  v a  2s . c o  m
 * 
 * @see com.fasterxml.jackson.databind.deser.BeanDeserializer
 */
public Rate(final double rate) {
    this(BigDecimal.valueOf(rate), SI.HERTZ);
}

From source file:mayoapp.migrations.V0400_2024__move_order_items_to_own_table.java

@Override
public void migrate(Connection connection) throws Exception {
    connection.setAutoCommit(false);/* w  w w.j  ava2  s.co m*/

    Statement queryStatement = connection.createStatement();
    ResultSet data = queryStatement.executeQuery("SELECT * from purchase_order");

    List<Order> orders = Lists.newArrayList();
    List<OrderItem> orderItems = Lists.newArrayList();

    ObjectMapper mapper = new ObjectMapper();

    while (data.next()) {
        Order order = new Order();
        order.setId((UUID) data.getObject("entity_id"));

        String orderDataString = data.getString("order_data");
        Map<String, Object> orderData = mapper.readValue(orderDataString,
                new TypeReference<Map<String, Object>>() {
                });

        List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");

        for (Map<String, Object> item : items) {
            OrderItem orderItem = new OrderItem();

            orderItem.setId(UUID.randomUUID());
            orderItem.setOrderId(order.getId());

            if (item.containsKey("id") && String.class.isAssignableFrom(item.get("id").getClass())) {
                orderItem.setPurchasableId(UUID.fromString((String) item.get("id")));
            }
            orderItem.setType((String) item.get("type"));
            orderItem.setTitle((String) item.get("title"));
            orderItem.setQuantity(((Integer) item.get("quantity")).longValue());
            orderItem.setUnitPrice(BigDecimal.valueOf((Double) item.get("unitPrice")));
            orderItem.setItemTotal(BigDecimal.valueOf((Double) item.get("itemTotal")));
            if (item.containsKey("vatRate")) {
                orderItem.setVatRate(BigDecimal.valueOf((Double) item.get("vatRate")));
            }

            if (item.containsKey("addons")) {
                orderItem.addData("addons", convertAddonsToMap((List<Map<String, Object>>) item.get("addons")));
            }

            orderItems.add(orderItem);
        }

        orderData.remove("items");
        order.setOrderData(orderData);
        orders.add(order);
    }

    queryStatement.close();

    // 1. Update orders

    PreparedStatement updateOrders = connection
            .prepareStatement("UPDATE purchase_order SET order_data = CAST (? AS json) WHERE entity_id =?");

    for (Order order : orders) {
        updateOrders.setObject(1, mapper.writeValueAsString(order.getOrderData()));
        updateOrders.setObject(2, order.getId());
        updateOrders.addBatch();
    }

    updateOrders.executeBatch();

    // 2. Insert items

    PreparedStatement insertItems = connection.prepareStatement(
            "INSERT INTO purchase_order_item (id, order_id, purchasable_id, type, title, quantity, unit_price, "
                    + "item_total, vat_rate, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST (? as json))");

    for (OrderItem item : orderItems) {
        insertItems.setObject(1, item.getId());
        insertItems.setObject(2, item.getOrderId());
        insertItems.setObject(3, item.getPurchasableId());
        insertItems.setString(4, item.getType());
        insertItems.setString(5, item.getTitle());
        insertItems.setLong(6, item.getQuantity());
        insertItems.setBigDecimal(7, item.getUnitPrice());
        insertItems.setBigDecimal(8, item.getItemTotal());
        insertItems.setBigDecimal(9, item.getVatRate());
        insertItems.setString(10, mapper.writeValueAsString(item.getData()));
        insertItems.addBatch();
    }

    insertItems.executeBatch();
}

From source file:com.navercorp.pinpoint.web.mapper.stat.sampling.sampler.JoinCpuLoadSampler.java

private double roundToScale(double value) {
    return BigDecimal.valueOf(value).setScale(1, RoundingMode.HALF_UP).doubleValue();
}

From source file:net.eusashead.hateoas.springhalbuilder.model.LineItem.java

@JsonIgnore
@Transient
public BigDecimal getSubTotal() {
    return BigDecimal.valueOf(quantity * sku.getPrice().doubleValue());
}

From source file:io.coala.time.Rate.java

/**
 * {@link Rate} static factory method/*  w w w  .j av a 2 s  .  c o  m*/
 */
public static Rate of(final Number value, final Unit<Frequency> amount) {
    return of(BigDecimal.valueOf(value.doubleValue()), amount);
}

From source file:com.haulmont.timesheets.listener.TimeEntryListener.java

protected void setTimeInHours(TimeEntry entity) {
    BigDecimal minutes = BigDecimal.valueOf(entity.getTimeInMinutes()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    entity.setTimeInHours(minutes.divide(MINUTES_IN_HOUR, BigDecimal.ROUND_HALF_DOWN));
}

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

@Test
public void createTrustLineIncorrectApiKey() {
    final TrustLineConfiguration trustLine = new TrustLineConfiguration(BigDecimal.valueOf(100));

    String issuer = "blub";

    given().header(CONTENT_TYPE_HEADER).header(API_KEY_HEADER_LABEL, "wrong_key")
            .header(TENANT_ID_HEADER_LABEL, firstTenantId).pathParameter("assetCode", ASSET_CODE)
            .pathParameter("issuer", issuer).body(trustLine)
            .put("/modules/stellarbridge/trustlines/{assetCode}/{issuer}/").then().assertThat()
            .statusCode(HttpStatus.UNAUTHORIZED.value());
}

From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremeRevenuFamille2000Test.java

@Test
public void couple() {
    assertThat(baremeCouple.calcul(BigDecimal.valueOf(revenu))).isEqualTo(impot);
}

From source file:pe.gob.mef.gescon.hibernate.impl.ConocimientoDaoImpl.java

@Override
public List<Tconocimiento> getTconocimientosActivedPublic() throws Exception {
    DetachedCriteria criteria = DetachedCriteria.forClass(Tconocimiento.class);
    criteria.add(Restrictions.eq("nactivo", BigDecimal.valueOf(Long.parseLong(Constante.ESTADO_ACTIVO))));
    criteria.add(//  www .  ja v a 2  s  .  c o m
            Restrictions.eq("nsituacionid", BigDecimal.valueOf(Long.parseLong(Constante.SITUACION_PUBLICADO))));
    criteria.addOrder(Order.desc("nconocimientoid"));
    return (List<Tconocimiento>) getHibernateTemplate().findByCriteria(criteria);
}