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.opengamma.examples.loader.ExampleCDSLoader.java

protected ManageablePosition makePositionAndTrade(Security security) {

    int shares = (RandomUtils.nextInt(490) + 10) * 10;
    ExternalIdBundle bundle = security.getExternalIdBundle();

    ManageablePosition position = new ManageablePosition(BigDecimal.valueOf(shares), bundle);
    ManageableTrade trade = new ManageableTrade(BigDecimal.valueOf(shares), bundle, LocalDate.of(2010, 12, 3),
            null, ExternalId.of("CPARTY", "BACS"));
    position.addTrade(trade);/*from   w w w. j a va  2  s .  c  o  m*/

    return position;
}

From source file:eu.bittrade.libs.steemj.protocol.Asset.java

/**
 * Set the amount of this asset.//  w w  w. j  av  a2s . c o  m
 * 
 * @param amount
 *            The amount.
 */
public void setAmount(BigDecimal amount) {
    if (amount.scale() > this.getPrecision()) {
        throw new InvalidParameterException("The provided 'amount' has a 'scale' of " + amount.scale()
                + ", but needs to have a 'scale' of " + this.getPrecision() + " when " + this.getSymbol().name()
                + " is used as a AssetSymbolType.");
    }

    this.amount = amount.multiply(BigDecimal.valueOf(Math.pow(10, this.getPrecision()))).longValue();
}

From source file:com.p5solutions.core.utils.NumberUtils.java

/**
 * Parses the number.//from   w  w  w .  jav  a 2s  . co  m
 * 
 * @param number
 *          the number
 * @param clazz
 *          the clazz
 * @return the object
 */
@SuppressWarnings("unchecked")
public static <T> T valueOf(String number, Class<?> clazz) {

    // if the string representation of the number is empty or null
    // then return a null, as it cannot be parsed by the <ClassNumber>.valueOf()
    if (Comparison.isEmptyOrNullTrim(number)) {
        return (T) null;
    }

    if (ReflectionUtility.isByteClass(clazz)) {
        return (T) Byte.valueOf(number);
    } else if (ReflectionUtility.isShortClass(clazz)) {
        return (T) Short.valueOf(number);
    } else if (ReflectionUtility.isIntegerClass(clazz)) {
        return (T) Integer.valueOf(number);
    } else if (ReflectionUtility.isLongClass(clazz)) {
        return (T) Long.valueOf(number);
    } else if (ReflectionUtility.isFloatClass(clazz)) {
        return (T) Short.valueOf(number);
    } else if (ReflectionUtility.isDoubleClass(clazz)) {
        return (T) Double.valueOf(number);
    } else if (ReflectionUtility.isBigDecimalClass(clazz)) {
        return (T) BigDecimal.valueOf(Double.valueOf(number));
    }

    return (T) null;
}

From source file:com.seyren.api.bean.SubscriptionsBean.java

@Override
public Response testSubscription(@PathParam("checkId") String checkId,
        @PathParam("subscriptionId") final String subscriptionId) {
    Check check = checksStore.getCheck(checkId);
    if (check == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }// www . j  ava  2s  .  c o m
    Collection<Subscription> subscriptions = Collections2.filter(check.getSubscriptions(),
            new Predicate<Subscription>() {
                @Override
                public boolean apply(Subscription subscription) {
                    return subscription.getId().equals(subscriptionId);
                }
            });
    if (subscriptions.size() != 1) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    check.setState(AlertType.ERROR);
    Subscription subscription = subscriptions.iterator().next();
    List<Alert> interestingAlerts = new ArrayList<Alert>();
    Alert alert = new Alert().withTarget(check.getTarget()).withValue(BigDecimal.valueOf(0.0))
            .withWarn(check.getWarn()).withError(check.getError()).withFromType(AlertType.OK)
            .withToType(AlertType.ERROR).withTimestamp(new DateTime());
    interestingAlerts.add(alert);
    for (NotificationService notificationService : notificationServices) {
        if (notificationService.canHandle(subscription.getType())) {
            try {
                notificationService.sendNotification(check, subscription, interestingAlerts);
            } catch (Exception e) {
                LOGGER.warn("Notifying {} by {} failed.", subscription.getTarget(), subscription.getType(), e);
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                        .entity(String.format("Notifying failed '%s'", e.getMessage()))
                        .type(MediaType.TEXT_PLAIN).build();
            }
        }
    }
    return Response.noContent().build();
}

From source file:churashima.action.manage.ReportAction.java

@Execute(validator = false)
public String attendance() {
    String ym = reportForm.ym;/*from w  w  w.  j  ava 2  s. c  o m*/

    int year = Integer.parseInt(ym.substring(0, 4));
    int month = Integer.parseInt(ym.substring(4));

    Calendar calFrom = Calendar.getInstance();
    calFrom.set(Calendar.YEAR, year);
    calFrom.set(Calendar.MONTH, month - 1);
    calFrom.set(Calendar.DAY_OF_MONTH, 1);
    Calendar calTo = Calendar.getInstance();
    calTo.set(Calendar.YEAR, year);
    calTo.set(Calendar.MONTH, month);
    calTo.set(Calendar.DAY_OF_MONTH, 1);

    WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class);
    List<ReportDto> reportDtoList = workDao.selectForReportAttendance(reportForm.kind, calFrom.getTime(),
            calTo.getTime());

    BigDecimal workHourTotal = BigDecimal.valueOf(0);
    BigDecimal overHourTotal = BigDecimal.valueOf(0);
    BigDecimal overHourMorningTotal = BigDecimal.valueOf(0);
    BigDecimal overHourEveningTotal = BigDecimal.valueOf(0);
    BigDecimal overHourNightTotal = BigDecimal.valueOf(0);

    for (ReportDto dto : reportDtoList) {
        workHourTotal = workHourTotal.add(dto.workHourTotal);
        overHourTotal = overHourTotal.add(dto.overHourTotal);
        overHourMorningTotal = overHourMorningTotal.add(dto.overHourMorningTotal);
        overHourEveningTotal = overHourEveningTotal.add(dto.overHourEveningTotal);
        overHourNightTotal = overHourNightTotal.add(dto.overHourNightTotal);
    }

    reportForm.workHourTotal = workHourTotal;
    reportForm.overHourTotal = overHourTotal;
    reportForm.overHourMorningTotal = overHourMorningTotal;
    reportForm.overHourEveningTotal = overHourEveningTotal;
    reportForm.overHourNightTotal = overHourNightTotal;

    // ?????
    calFrom.add(Calendar.MONTH, -1);
    calTo.add(Calendar.MONTH, -1);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    int count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(), null);
    if (count > 0) {
        reportForm.ymBefore = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymBefore = null;
    }

    // ????
    calFrom.add(Calendar.MONTH, +2);
    calTo.add(Calendar.MONTH, +2);
    count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(), null);
    if (count > 0) {
        reportForm.ymNext = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymNext = null;
    }

    reportForm.reportDtoList = reportDtoList;

    return "attendanceReport.jsp";
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.ValueThresholdsLowLevelAbstractionConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    ValueThresholdsLowLevelAbstractionConverter converter = new ValueThresholdsLowLevelAbstractionConverter();
    converter.setConverterVisitor(converterVisitor);

    SystemProposition primParam = new SystemProposition();
    primParam.setId(1L);//from  w  w w.  ja  va  2 s.com
    primParam.setKey("test-primparam1");
    primParam.setInSystem(true);
    primParam.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    TimeUnit dayUnit = new TimeUnit();
    dayUnit.setName("day");

    ValueThresholdGroupEntity thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(2L);
    thresholdGroup.setKey("test-valuethreshold");
    userConstraintName = asValueString(thresholdGroup);
    compConstraintName = asValueCompString(thresholdGroup);

    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    ValueThresholdEntity threshold = new ValueThresholdEntity();
    threshold.setAbstractedFrom(primParam);
    threshold.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold.setMinValueComp(gt);
    threshold.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold.setMaxValueComp(lt);

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold);
    thresholdGroup.setValueThresholds(thresholds);
    llaDefs = converter.convert(thresholdGroup);
    String toPropositionId = toPropositionId("test-valuethreshold");
    for (PropositionDefinition propDef : llaDefs) {
        if (propDef.getId().equals(toPropositionId)) {
            llaDef = (LowLevelAbstractionDefinition) propDef;
            break;
        }
    }
}

From source file:com.roncoo.pay.controller.common.BaseController2.java

public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
    String resultStr = getRequest().getParameter(name);
    if (resultStr != null) {
        try {/* ww  w. j a v  a2s . com*/
            return BigDecimal.valueOf(Double.parseDouble(resultStr));
        } catch (Exception e) {
            log.error("??:", e);
            return defaultValue;
        }
    }
    return defaultValue;
}

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

private static BigDecimal budget(Money money) {
    int budget = (money != null) ? money.getValue() : 0;
    return BigDecimal.valueOf(budget).divide(Money.MONEY_VALUE_FACTOR);
}

From source file:com.khartec.waltz.service.complexity.ComplexityRatingService.java

private static ComplexityScoreRecord buildComplexityScoreRecord(ComplexityScore r, ComplexityKind kind) {
    ComplexityScoreRecord record = new ComplexityScoreRecord();
    record.setEntityKind(EntityKind.APPLICATION.name());
    record.setEntityId(r.id());//from   w  w w .  j av  a2s  . c om
    record.setComplexityKind(kind.name());
    record.setScore(BigDecimal.valueOf(r.score()));
    return record;
}

From source file:org.brekka.stillingar.example.FieldTypesDOMTest.java

private static Testing writeConfig() {
    Random r = new Random();
    ConfigurationDocument doc = ConfigurationDocument.Factory.newInstance();
    Configuration newConfiguration = doc.addNewConfiguration();
    FeatureFlagType featureFlag = newConfiguration.addNewFeatureFlag();
    featureFlag.setKey("turbo");
    featureFlag.setBooleanValue(true);//w w  w  . j  a v  a 2  s .  com
    Testing testing = newConfiguration.addNewTesting();
    testing.setAnyURI("http://brekka.org/" + RandomStringUtils.randomAlphanumeric(10));
    testing.setBoolean(r.nextBoolean());
    testing.setByte((byte) r.nextInt());
    Calendar cal = Calendar.getInstance();
    testing.setDate(cal);
    testing.setDateTime(cal);
    testing.setDecimal(BigDecimal.valueOf(r.nextDouble()));
    testing.setDouble(r.nextDouble());
    testing.setFloat(r.nextFloat());
    testing.setInt(r.nextInt());
    testing.setInteger(BigInteger.valueOf(r.nextLong()));
    testing.setLanguage("en");
    testing.setLong(r.nextLong());
    testing.setShort((short) r.nextInt());
    testing.setString(RandomStringUtils.randomAlphanumeric(24));
    testing.setTime(cal);
    testing.setUUID(UUID.randomUUID().toString());
    testing.setPeriod(new GDuration("P5Y2M10DT15H"));
    byte[] binary = new byte[32];
    r.nextBytes(binary);
    testing.setBinary(binary);
    TestSupport.write(doc);
    return testing;
}