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.camelcookbook.transformation.csv.CsvSpringTest.java

@Test
public void testCsvUnmarshal() throws Exception {
    final String request = "PROGRAMMING,Camel in Action,en,Claus Ibsen,Jon Anstey,Dec-2010,49.99\n"
            + "PROGRAMMING,Apache Camel Developer's Cookbook,en,Scott Cranton,Jakub Korab,Dec-2013,49.99\n";

    @SuppressWarnings("unchecked")
    final List<BookModel> response = Collections
            .checkedList(template.requestBody("direct:unmarshal", request, List.class), BookModel.class);

    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM-yyyy");

    BookModel book1 = new BookModel();
    book1.setCategory("PROGRAMMING");
    book1.setTitle("Camel in Action");
    book1.setTitleLanguage("en");
    book1.setAuthor1("Claus Ibsen");
    book1.setAuthor2("Jon Anstey");
    book1.setPublishDate(simpleDateFormat.parse("Dec-2010"));
    book1.setPrice(BigDecimal.valueOf(49.99));

    BookModel book2 = new BookModel();
    book2.setCategory("PROGRAMMING");
    book2.setTitle("Apache Camel Developer's Cookbook");
    book2.setTitleLanguage("en");
    book2.setAuthor1("Scott Cranton");
    book2.setAuthor2("Jakub Korab");
    book2.setPublishDate(simpleDateFormat.parse("Dec-2013"));
    book2.setPrice(BigDecimal.valueOf(49.99));

    BookModel response1 = response.get(0);
    assertEquals(book1, response1);//from   w w  w.j av a 2  s .co m

    BookModel response2 = response.get(1);
    assertEquals(book2, response2);
}

From source file:net.ceos.project.poi.annotated.bean.AutomaticPositionObjectBuilder.java

/**
 * Create a PerformanceObject for tests.
 * /* w w  w .  ja  va  2 s  .c o  m*/
 * @return the {@link PerformanceObject}
 */
public static AutomaticPositionObject buildAutomaticPositionObject(int multiplier) {
    AutomaticPositionObject toValidate = new AutomaticPositionObject();

    toValidate.setDateAttribute1(new Date());
    toValidate.setDateAttribute2(new Date());
    toValidate.setDateAttribute3(new Date());

    toValidate.setStringAttribute1("some string");
    toValidate.setStringAttribute2("some string");
    toValidate.setStringAttribute3("some string");
    toValidate.setStringAttribute4("some string");
    toValidate.setStringAttribute5("some string");
    toValidate.setStringAttribute6("some string");
    toValidate.setStringAttribute7("some string");
    toValidate.setStringAttribute8("some string");
    toValidate.setStringAttribute9("some string");
    toValidate.setStringAttribute10("some string");
    toValidate.setStringAttribute11("some string");
    toValidate.setStringAttribute12("some string");

    toValidate.setIntegerAttribute1(6 * multiplier);
    toValidate.setIntegerAttribute2(11 * multiplier);
    toValidate.setIntegerAttribute3(33 * multiplier);
    toValidate.setIntegerAttribute4(46 * multiplier);
    toValidate.setIntegerAttribute5(2 * multiplier);
    toValidate.setIntegerAttribute6(7 * multiplier);
    toValidate.setIntegerAttribute7(9 * multiplier);

    toValidate.setDoubleAttribute1(Double.valueOf("11.3") * multiplier);
    toValidate.setDoubleAttribute2(Double.valueOf("237.131") * multiplier);
    toValidate.setDoubleAttribute3(Double.valueOf("25.777") * multiplier);

    toValidate.setLongAttribute(Long.valueOf("1234567890") * multiplier);

    toValidate.setBooleanAttribute1(Boolean.TRUE);
    toValidate.setBooleanAttribute2(Boolean.TRUE);
    toValidate.setBooleanAttribute3(Boolean.FALSE);
    toValidate.setBooleanAttribute4(Boolean.TRUE);
    /* create sub object Job */
    Job job = new Job();
    job.setJobCode(0005);
    job.setJobFamily("Family Job Name");
    job.setJobName("Job Name");
    toValidate.setJob(job);
    toValidate.setIntegerPrimitiveAttribute1(2 * multiplier);
    toValidate.setIntegerPrimitiveAttribute2(3 * multiplier);
    toValidate.setIntegerPrimitiveAttribute3(11 * multiplier);
    toValidate.setIntegerPrimitiveAttribute4(5 * multiplier);
    toValidate.setIntegerPrimitiveAttribute5(12 * multiplier);

    toValidate.setDoublePrimitiveAttribute(44.6 * multiplier);

    toValidate.setLongPrimitiveAttribute(987654321L * multiplier);

    toValidate.setBooleanPrimitiveAttribute(true);
    /* create sub object AddressInfo */
    AddressInfo ai = new AddressInfo();
    ai.setAddress("this is the street");
    ai.setNumber(99);
    ai.setCity("this is the city");
    ai.setCityCode(70065);
    ai.setCountry("This is a Country");
    toValidate.setAddressInfo(ai);
    toValidate.setFloatAttribute(14.765f * multiplier);
    toValidate.setFloatPrimitiveAttribute(11.1125f * multiplier);
    toValidate.setUnitFamily(UnitFamily.COMPONENTS);
    toValidate.setBigDecimalAttribute(BigDecimal.valueOf(24.777).multiply(BigDecimal.valueOf(multiplier)));
    // TODO add new fields below

    return toValidate;
}

From source file:com.prowidesoftware.swift.model.CurrencyAmount.java

/**
 * @param currency a not null currency code
 * @param value the value for the amount, may be <code>null</code>
 *//*from ww  w . j  a  v a 2s . c  o  m*/
CurrencyAmount(final String currency, Number amount) {
    super();
    this.currency = currency;
    if (amount == null) {
        this.amount = BigDecimal.ZERO;
    } else {
        if (amount instanceof BigDecimal) {
            this.amount = (BigDecimal) amount;
        } else if (amount instanceof Long) {
            this.amount = new BigDecimal(((Long) amount).longValue());
        } else if (amount instanceof Integer) {
            this.amount = new BigDecimal(((Integer) amount).intValue());
        } else if (amount instanceof Short) {
            this.amount = new BigDecimal(((Short) amount).intValue());
        } else if (amount instanceof Double) {
            /*
             * we use valueOf instead of constructor because it uses a string under the covers to eliminate floating point rounding errors
             */
            this.amount = BigDecimal.valueOf(((Double) amount).doubleValue());
        } else {
            throw new IllegalArgumentException("class " + amount.getClass().getName() + " is not supported");
        }
    }
}

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

@Override
public List<Tconocimiento> getTconocimientosActivedPublicByType(BigDecimal type) throws Exception {
    DetachedCriteria criteria = DetachedCriteria.forClass(Tconocimiento.class);
    criteria.add(Restrictions.eq("ntipoconocimientoid", type));
    criteria.add(Restrictions.eq("nactivo", BigDecimal.valueOf(Long.parseLong(Constante.ESTADO_ACTIVO))));
    criteria.add(//  w w w  .j  ava 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);
}

From source file:com.exxonmobile.ace.hybris.facades.product.populators.ProductPriceRangePopulator.java

protected PriceData createPriceData(final PriceDataType priceType, final PriceInformation priceInfo) {
    return getPriceDataFactory().create(priceType, BigDecimal.valueOf(priceInfo.getPriceValue().getValue()),
            priceInfo.getPriceValue().getCurrencyIso());
}

From source file:it.polimi.diceH2020.SPACE4Cloud.shared.solution.Solution.java

public String toStringReduced() {
    StringJoiner sj = new StringJoiner("\t", "", "");
    sj.add("solID=" + id).add("solFeas=" + this.isFeasible().toString())
            .add("cost=" + BigDecimal.valueOf(this.getCost()).toString());
    sj.add("totalDuration=" + this.getOptimizationTime().toString());
    lstPhases.forEach(ph -> sj.add("phase=" + ph.getId().toString()).add("duration=" + ph.getDuration()));
    lstSolutions.forEach(s -> sj.add("jobClass=" + s.getId()).add("typeVM=" + s.getTypeVMselected().getId())
            .add("numVM=" + s.getNumberVM()).add("numReserved=" + s.getNumReservedVM())
            .add("numOnDemand=" + s.getNumOnDemandVM()).add("numSpot=" + s.getNumSpotVM())
            .add("jobFeas=" + s.getFeasible().toString()));
    return sj.toString();
}

From source file:com.ocs.dynamo.importer.impl.BaseImporter.java

@SuppressWarnings("unchecked")
private Object getFieldValue(PropertyDescriptor d, U unit, XlsField field) {
    Object obj = null;/* w ww .  j  a va2  s.com*/
    if (String.class.equals(d.getPropertyType())) {
        String value = getStringValueWithDefault(unit, field);
        if (value != null) {
            value = value.trim();
        }
        obj = StringUtils.isEmpty(value) ? null : value;
    } else if (d.getPropertyType().isEnum()) {
        String value = getStringValueWithDefault(unit, field);
        if (value != null) {
            value = value.trim();
            try {
                obj = Enum.valueOf(d.getPropertyType().asSubclass(Enum.class), value.toUpperCase());
            } catch (IllegalArgumentException ex) {
                throw new OCSImportException(
                        "Value " + value + " cannot be translated to a valid enumeration value", ex);
            }
        }

    } else if (Number.class.isAssignableFrom(d.getPropertyType())) {
        // numeric field

        Double value = getNumericValueWithDefault(unit, field);
        if (value != null) {

            // if the field represents a percentage but it is
            // received as a
            // fraction, we multiply it by 100
            if (field.percentage()) {
                if (isPercentageCorrectionSupported()) {
                    value = PERCENTAGE_FACTOR * value;
                }
            }

            // illegal negative value
            if (field.cannotBeNegative() && value < 0.0) {
                throw new OCSImportException(
                        "Negative value " + value + " found for field '" + d.getName() + "'");
            }

            if (Integer.class.equals(d.getPropertyType())) {
                obj = new Integer(value.intValue());
            } else if (BigDecimal.class.equals(d.getPropertyType())) {
                obj = BigDecimal.valueOf(value.doubleValue());
            } else {
                // by default, use a double
                obj = value;
            }
        }
    } else if (Boolean.class.isAssignableFrom(d.getPropertyType())) {
        return getBooleanValueWithDefault(unit, field);
    }
    return obj;
}

From source file:com.opensymphony.xwork2.conversion.impl.NumberConverterTest.java

public void testStringToBigDecimalConversionWithCommasEN() throws Exception {
    // given/*from   w  w  w.  j a  va2s.c o m*/
    NumberConverter converter = new NumberConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("en", "US"));

    // when
    Object value = converter.convertValue(context, null, null, null, "100,234.4", BigDecimal.class);

    // then
    assertEquals(BigDecimal.valueOf(100234.4), value);
}

From source file:com.stratio.cassandra.lucene.schema.mapping.BigDecimalMapper.java

/**
 * Builds a new {@link BigDecimalMapper} using the specified max number of digits for the integer and decimal
 * parts.// w  w  w.  j  a v  a  2s  . c  om
 *
 * @param field         The name of the field.
 * @param column        The name of the column to be mapped.
 * @param indexed       If the field supports searching.
 * @param sorted        If the field supports sorting.
 * @param integerDigits The max number of digits for the integer part. If {@code null}, the {@link
 *                      #DEFAULT_INTEGER_DIGITS} will be used.
 * @param decimalDigits The max number of digits for the decimal part. If {@code null}, the {@link
 *                      #DEFAULT_DECIMAL_DIGITS} will be used.
 */
public BigDecimalMapper(String field, String column, Boolean indexed, Boolean sorted, Integer integerDigits,
        Integer decimalDigits) {
    super(field, column, indexed, sorted, AsciiType.instance, UTF8Type.instance, Int32Type.instance,
            LongType.instance, IntegerType.instance, FloatType.instance, DoubleType.instance,
            DecimalType.instance);

    // Setup integer part mapping
    if (integerDigits != null && integerDigits <= 0) {
        throw new IndexException("Positive integer part digits required");
    }
    this.integerDigits = integerDigits == null ? DEFAULT_INTEGER_DIGITS : integerDigits;

    // Setup decimal part mapping
    if (decimalDigits != null && decimalDigits <= 0) {
        throw new IndexException("Positive decimal part digits required");
    }
    this.decimalDigits = decimalDigits == null ? DEFAULT_DECIMAL_DIGITS : decimalDigits;

    int totalDigits = this.integerDigits + this.decimalDigits;
    BigDecimal divisor = BigDecimal.valueOf(BASE).pow(this.decimalDigits);
    BigDecimal dividend = BigDecimal.valueOf(BASE).pow(totalDigits).subtract(BigDecimal.valueOf(1));
    complement = dividend.divide(divisor);
}

From source file:com.trenako.web.controllers.form.WishListFormTests.java

@Test
public void shouldEditWishListUsingTheFormValues() {
    WishListForm form = WishListForm.newForm(privateWishList(), messageSource);
    form.setBudget(BigDecimal.valueOf(250.50));
    form.setWishList(wishList());/*from  w w  w  .ja  v a 2 s.co m*/

    WishList wishList = form.buildWishList(owner());

    assertEquals("bob-my-list", wishList.getSlug());
    assertEquals("bob", wishList.getOwner());
    assertEquals("EUR250.50", wishList.getBudget().toString());
    assertEquals("public", wishList.getVisibility());
}