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.gst.portfolio.shareproducts.serialization.ShareProductDataSerializer.java

public ShareProduct validateAndCreate(JsonCommand jsonCommand) {
    if (StringUtils.isBlank(jsonCommand.json())) {
        throw new InvalidJsonException();
    }/*from www .  j  a  v a  2 s.c o  m*/
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(),
            ShareProductApiConstants.supportedParametersForCreate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("sharesproduct");
    JsonElement element = jsonCommand.parsedJson();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject());
    final String productName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.name_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.name_paramname).value(productName).notBlank()
            .notExceedingLengthOf(200);
    final String shortName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.shortname_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName)
            .notBlank().notExceedingLengthOf(4);
    String description = null;
    if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.description_paramname, element)) {
        description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname,
                element);
    }

    String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname,
            element);
    // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank();

    Long totalNumberOfShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname)
            .value(totalNumberOfShares).notNull().longGreaterThanZero();
    final Long sharesIssued = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element);
    if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname)
                .value(sharesIssued).failWithCodeNoParameterAddedToErrorCode(
                        "sharesIssued.cannot.be.greater.than.totalNumberOfShares");
    }
    final String currencyCode = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.currency_paramname, element);
    final Integer digitsAfterDecimal = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element);
    final Integer inMultiplesOf = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element);
    final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf);

    final BigDecimal unitPrice = this.fromApiJsonHelper
            .extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.unitprice_paramname).value(unitPrice).notNull()
            .positiveAmount();

    BigDecimal shareCapitalValue = BigDecimal.ONE;
    if (sharesIssued != null && unitPrice != null) {
        shareCapitalValue = BigDecimal.valueOf(sharesIssued).multiply(unitPrice);
    }

    Integer accountingRule = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.accountingRuleParamName, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.accountingRuleParamName).value(accountingRule)
            .notNull().integerGreaterThanZero();
    AccountingRuleType accountingRuleType = null;
    if (accountingRule != null) {
        accountingRuleType = AccountingRuleType.fromInt(accountingRule);
    }

    Long minimumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.minimumshares_paramname, element);
    Long nominalClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.nominaltshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
            .value(nominalClientShares).notNull().longGreaterThanZero();
    if (minimumClientShares != null && nominalClientShares != null
            && !minimumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
                .value(nominalClientShares).longGreaterThanNumber(minimumClientShares);
    }
    Long maximumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.maximumshares_paramname, element);
    if (maximumClientShares != null && nominalClientShares != null
            && !maximumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.maximumshares_paramname)
                .value(maximumClientShares).longGreaterThanNumber(nominalClientShares);
    }

    Set<ShareProductMarketPrice> marketPriceSet = asembleShareMarketPrice(element);
    Set<Charge> charges = assembleListOfProductCharges(element, currencyCode);
    Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed(
            ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element);

    Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed(
            ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale);
    PeriodFrequencyType minimumActivePeriodType = extractPeriodType(
            ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element);
    if (minimumActivePeriod != null) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname)
                .value(minimumActivePeriodType.getValue())
                .integerSameAsNumber(PeriodFrequencyType.DAYS.getValue());
    }

    Integer lockinPeriod = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.lockperiod_paramname, element, locale);
    PeriodFrequencyType lockPeriodType = extractPeriodType(
            ShareProductApiConstants.lockinperiodfrequencytype_paramname, element);

    AppUser createdBy = platformSecurityContext.authenticatedUser();
    AppUser modifiedBy = createdBy;
    DateTime createdDate = DateUtils.getLocalDateTimeOfTenant().toDateTime();
    DateTime modifiedOn = createdDate;
    ShareProduct product = new ShareProduct(productName, shortName, description, externalId, currency,
            totalNumberOfShares, sharesIssued, unitPrice, shareCapitalValue, minimumClientShares,
            nominalClientShares, maximumClientShares, marketPriceSet, charges, allowdividendsForInactiveClients,
            lockinPeriod, lockPeriodType, minimumActivePeriod, minimumActivePeriodType, createdBy, createdDate,
            modifiedBy, modifiedOn, accountingRuleType);

    for (ShareProductMarketPrice data : marketPriceSet) {
        data.setShareProduct(product);
    }
    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
    return product;
}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeTime.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;/*from  w w w. ja  v a2 s .c o  m*/
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }

    // set date to 01.01.1970
    calendar = (Calendar) calendar.clone();
    calendar.set(1970, 0, 1);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.SECOND))[0],
                    bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.SECOND))[0],
                    charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, MINUTES) || StringUtils.equals(variant, MINUTES_SHORT)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1970, 0, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            long millisMidnight = calendar.getTimeInMillis();

            BigDecimal minutes = new BigDecimal(millis - millisMidnight);

            // milliseconds to minutes
            minutes = minutes.divide(BigDecimal.valueOf(1000 * 60), 0, RoundingMode.HALF_UP);

            // xxx
            minutes = minutes.divide(minuteMultiplier, 0, RoundingMode.HALF_UP);

            if (StringUtils.equals(variant, MINUTES_SHORT)) {
                result = charType.encode(minutes);
            } else {
                result = wordType.encode(minutes);
            }

        }
    }

    return result;
}

From source file:net.drgnome.virtualpack.util.Util.java

public static String printDouble(double d) {
        return BigDecimal.valueOf(smoothBig(d, 3)).toPlainString();
    }

From source file:it.geosolutions.geoserver.rest.encoder.feature.GSFeatureEncoderTest.java

@Test
public void testFeatureTypeEncoder() {

    GSFeatureTypeEncoder encoder = new GSFeatureTypeEncoder();
    encoder.addKeyword("KEYWORD_1");
    encoder.addKeyword("KEYWORD_2");
    encoder.addKeyword("...");
    encoder.addKeyword("KEYWORD_N");

    encoder.setName("Layername");

    encoder.setTitle("title");
    encoder.addKeyword("TODO");
    encoder.setNativeCRS("EPSG:4326");
    encoder.setDescription("desc");
    encoder.setEnabled(true);//from  w w  w  .j  a va 2 s  .co m

    GSAttributeEncoder attribute = new GSAttributeEncoder();
    attribute.setAttribute(FeatureTypeAttribute.name, "NAME");
    attribute.setAttribute(FeatureTypeAttribute.binding, "java.lang.String");
    attribute.setAttribute(FeatureTypeAttribute.maxOccurs, "1");
    attribute.setAttribute(FeatureTypeAttribute.minOccurs, "0");
    attribute.setAttribute(FeatureTypeAttribute.nillable, "true");

    encoder.setAttribute(attribute);

    encoder.delAttribute("NAME");

    attribute.setAttribute(FeatureTypeAttribute.name, "NEW_NAME");

    encoder.setAttribute(attribute);

    // TODO encoder.getAttribute("NAME");

    GSFeatureDimensionInfoEncoder dim2 = new GSFeatureDimensionInfoEncoder("ELE");

    encoder.setMetadataDimension("elevation", dim2);
    dim2.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(10));
    Element el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION);
    assertNotNull(el);

    LOGGER.info("contains_key:" + el.toString());

    dim2.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(12));
    el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION);
    assertNotNull(el);
    assertEquals("12", el.getText());

    dim2.setPresentation(Presentation.CONTINUOUS_INTERVAL);

    encoder.setMetadataDimension("time", new GSFeatureDimensionInfoEncoder("time"));
    el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION);
    assertNotNull(el);
    el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION);
    assertNull(el);

    el = ElementUtils.contains(encoder.getRoot(), GSResourceEncoder.METADATA);
    assertNotNull(el);
    LOGGER.info("contains_key:" + el.toString());

    final boolean removed = ElementUtils.remove(encoder.getRoot(), el);
    LOGGER.info("remove:" + removed);
    assertTrue(removed);

    el = ElementUtils.contains(encoder.getRoot(), "metadata");
    assertNull(el);
    if (el == null)
        LOGGER.info("REMOVED");

    if (LOGGER.isInfoEnabled())
        LOGGER.info(encoder.toString());

    assertEquals(encoder.getName(), "Layername");
}

From source file:com.espertech.esper.regression.expr.TestFilterExpressionsOptimizable.java

public void testPatternUDFFilterOptimizable() {
    epService.getEPAdministrator().getConfiguration().addPlugInSingleRowFunction("myCustomBigDecimalEquals",
            this.getClass().getName(), "myCustomBigDecimalEquals");

    String epl = "select * from pattern[a=SupportBean() -> b=SupportBean(myCustomBigDecimalEquals(a.bigDecimal, b.bigDecimal))]";
    epService.getEPAdministrator().createEPL(epl).addListener(listener);

    SupportBean beanOne = new SupportBean("E1", 0);
    beanOne.setBigDecimal(BigDecimal.valueOf(13));
    epService.getEPRuntime().sendEvent(beanOne);

    SupportBean beanTwo = new SupportBean("E2", 0);
    beanTwo.setBigDecimal(BigDecimal.valueOf(13));
    epService.getEPRuntime().sendEvent(beanTwo);

    assertTrue(listener.isInvoked());//from   w  w  w.ja v a  2 s .c o  m
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ExcelImportUtilities.java

/**
 * Creates a NumberAV object from the attrValue for the given number attribute type.
 * @param at The attribute to which the created number should be linked.
 * @param attrValue Cell value holder which contains the relevant number value
 * @param valueOverride an override value for the actual cell content. If this String is non-null/empty and non-whitespace, it will used in the NumberAV, regardless of the cell content in attrValue!
 * @return A number attribute value object containing the value from attrValue or valueOverride, or <code>null</code> if no number could be parsed
 *///w ww .  ja va 2  s . co  m
@SuppressWarnings("boxing")
private static NumberAV createNumberAV(NumberAT at, CellValueHolder attrValue, String valueOverride) {
    NumberAV numberV = new NumberAV();
    Double cell = null;
    // if valueOverride is null, use attrValue as "default value"
    String value = StringUtils.defaultIfBlank(valueOverride, attrValue.getAttributeValue());

    try {
        cell = contentAsDouble(value);
    } catch (NumberFormatException ex) {
        String warnMessage = "Cell [" + getCellRef(attrValue.getOriginCell()) + "]  Ignoring value " + value
                + " for attribute type " + at.getName() + " due to error:" + ex.getMessage();
        getProcessingLog().warn(warnMessage);
        attrValue.addProblem(ProblemMarker.WARNING, warnMessage);
        throw new IllegalArgumentException("\"" + value + "\" is not a number", ex);
    } catch (IllegalStateException ex) {
        String warnMessage = "Cell [" + getCellRef(attrValue.getOriginCell()) + "]  Ignoring value " + value
                + " for attribute type " + at.getName() + " due to error:" + ex.getMessage();
        getProcessingLog().warn(warnMessage);
        attrValue.addProblem(ProblemMarker.WARNING, warnMessage);
        throw new IllegalArgumentException(ex);
    }

    if (cell != null) {
        try {
            BigDecimal v = BigDecimal.valueOf(cell);
            numberV.setValue(v);

            return numberV;
        } catch (NumberFormatException e) {
            LOGGER.warn("Couldn't translate a Double into a BigDecimal");
        }
    }
    return null;
}

From source file:org.teavm.flavour.json.test.SerializerTest.java

@Test
public void serializesBuiltInTypes() {
    BuiltInTypes o = new BuiltInTypes();
    o.boolField = true;//from   w ww . j a v  a  2  s. c o  m
    o.byteField = 1;
    o.charField = '0';
    o.shortField = 2;
    o.intField = 3;
    o.longField = 4L;
    o.floatField = 5F;
    o.doubleField = 6.0;
    o.bigIntField = BigInteger.valueOf(7);
    o.bigDecimalField = BigDecimal.valueOf(8);
    o.list = Arrays.<Object>asList("foo", 1);
    o.map = new HashMap<>();
    o.map.put("key1", "value");
    o.map.put("key2", 23);
    o.set = new HashSet<>(Arrays.<Object>asList("bar", 2));

    JsonNode node = JSONRunner.serialize(o);

    assertEquals(true, node.get("boolField").asBoolean());
    assertEquals(1, node.get("byteField").asInt());
    assertEquals("0", node.get("charField").asText());
    assertEquals(2, node.get("shortField").asInt());
    assertEquals(3, node.get("intField").asInt());
    assertEquals(4, node.get("longField").asInt());
    assertEquals(5, node.get("floatField").asInt());
    assertEquals(6, node.get("doubleField").asInt());
    assertEquals(7, node.get("bigIntField").asInt());
    assertEquals(8, node.get("bigDecimalField").asInt());
    assertEquals(2, node.get("list").size());
    assertEquals("foo", node.get("list").get(0).textValue());
    assertEquals(1, node.get("list").get(1).intValue());
    assertEquals("value", node.get("map").get("key1").asText());
    assertEquals(23, node.get("map").get("key2").asInt());
    assertEquals(2, node.get("set").size());
}

From source file:de.hybris.platform.b2bacceleratorfacades.order.converters.populator.GroupOrderEntryPopulator.java

protected PriceData buildPrice(final PriceData base, final long amount) {
    return getPriceDataFactory().create(base.getPriceType(), BigDecimal.valueOf(amount), base.getCurrencyIso());
}

From source file:com.opengamma.examples.bloomberg.loader.ExampleBondPortfolioLoader.java

/**
 * Create a position of a random number of shares.
 * <p>// w  w w  .  ja  va2  s  .c o  m
 * This creates the position using a random number of units.
 * 
 * @param security  the security to add a position for, not null
 * @return the position, not null
 */
protected ManageablePosition createPosition(BondSecurity security) {
    s_logger.info("Creating position {}", security);
    int shares = (RandomUtils.nextInt(490) + 10) * 10;
    ExternalId buid = security.getExternalIdBundle().getExternalId(ExternalSchemes.BLOOMBERG_BUID);
    ExternalIdBundle bundle;
    if (buid != null) {
        bundle = ExternalIdBundle.of(buid);
    } else {
        bundle = security.getExternalIdBundle();
    }
    return new ManageablePosition(BigDecimal.valueOf(shares), bundle);
}

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

/**
 * Parse duration as {@link DecimalMeasure JSR-275} measure (e.g.
 * {@code "123 ms"}) or as ISO Period with
 * {@link org.threeten.bp.Duration#parse(CharSequence) JSR-310} or
 * {@link Period#parse(String) Joda}./* w  w  w  .  j av a  2  s  . co m*/
 * 
 * Examples of ISO period:
 * 
 * <pre>
 *    "PT20.345S" -> parses as "20.345 seconds"
 *    "PT15M"     -> parses as "15 minutes" (where a minute is 60 seconds)
 *    "PT10H"     -> parses as "10 hours" (where an hour is 3600 seconds)
 *    "P2D"       -> parses as "2 days" (where a day is 24 hours or 86400 seconds)
 *    "P2DT3H4M"  -> parses as "2 days, 3 hours and 4 minutes"
 *    "P-6H3M"    -> parses as "-6 hours and +3 minutes"
 *    "-P6H3M"    -> parses as "-6 hours and -3 minutes"
 *    "-P-6H+3M"  -> parses as "+6 hours and -3 minutes"
 * </pre>
 * 
 * @param measure the {@link String} representation of a duration
 * @return
 * 
 * @see org.threeten.bp.Duration#parse(String)
 * @see org.joda.time.format.ISOPeriodFormat#standard()
 * @see DecimalMeasure
 */
protected static final Measure<BigDecimal, Duration> parsePeriodOrMeasure(final String measure) {
    if (measure == null)
        return null;//throw new NullPointerException();
    DecimalMeasure<Duration> result;
    try {
        result = DecimalMeasure.valueOf(measure + " ");
        // LOG.trace("Parsed '{}' as JSR-275 measure/unit: {}", measure,
        // result);
        return result;
    } catch (final Exception a) {
        // LOG.trace("JSR-275 failed, try JSR-310", e);
        try {
            // final long millis = Period.parse(measure).getMillis();
            // return DecimalMeasure.valueOf(BigDecimal.valueOf(millis),
            // SI.MILLI(SI.SECOND));
            final java.time.Duration temp = java.time.Duration.parse(measure);
            result = temp.getNano() == 0
                    ? DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds()), SI.SECOND)
                    : DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds())
                            .multiply(BigDecimal.TEN.pow(9)).add(BigDecimal.valueOf(temp.getNano())),
                            Units.NANOS);
            // LOG.trace(
            // "Parsed '{}' using JSR-310 to JSR-275 measure/unit: {}",
            // measure, result);
            return result;
        } catch (final Exception e) {
            // LOG.trace("JSR-275 and JSR-310 failed, try Joda", e);
            try {
                final Period joda = Period.parse(measure);
                result = DecimalMeasure.valueOf(BigDecimal.valueOf(joda.toStandardDuration().getMillis()),
                        Units.MILLIS);
                // LOG.trace(
                // "Parsed '{}' using Joda to JSR-275 measure/unit: {}",
                // measure, result);
                return result;
            } catch (final Exception j) {
                return Thrower.throwNew(IllegalArgumentException.class,
                        "Could not parse duration or period from: {}"
                                + ", JSR-275: {}, JSR-310: {}, Joda-time: {}",
                        measure, a.getMessage(), e.getMessage(), j.getMessage());
            }
        }
    }
}