List of usage examples for java.math BigDecimal valueOf
public static BigDecimal valueOf(double val)
From source file:fragment.web.AbstractProductsControllerTest.java
private Product productCreation(String productCode, boolean hasCharges, Long serviceUsageTypeID, Long serviceInstanceId, String conversionFactor, boolean hasDiscriminator, String discriminator, String discriminatorDisplayName) throws Exception { Product product = new Product("New", "New_Prod", "New_Prod", "", getRootUser()); product.setCode(productCode);/*from w w w . j ava2 s .co m*/ product.setServiceInstance(serviceInstanceDAO.find(serviceInstanceId)); product.setUom("Hours"); Category category = productsService.getAllCategories().get(0); product.setCategory(category); ProductForm form = new ProductForm(product); form.setStartDate(new Date()); form.setServiceUUID(serviceDAO.find(6000L).getUuid()); form.setServiceInstanceUUID(serviceInstanceDAO.find(1L).getUuid()); form.setCategoryID(category.getId().toString()); form.setConversionFactor("1"); List<ProductCharge> productCharges = new ArrayList<ProductCharge>(); if (hasCharges) { ProductCharge productCharge = new ProductCharge(); productCharge.setRevision(revisionDAO.getCurrentRevision(null)); productCharge.setCatalog(null); productCharge.setCurrencyValue(currencyValueDAO.find(1L)); productCharge.setPrice(BigDecimal.valueOf(100)); productCharge.setCreatedAt(new Date()); productCharge.setCreatedBy(getRootUser()); productCharge.setUpdatedBy(getRootUser()); productsService.saveProductCharge(productCharge); productCharges.add(productCharge); } form.setProductCharges(productCharges); form.setIsNewProduct(true); ServiceInstance serviceInstance = serviceInstanceDAO.find(serviceInstanceId); Service service = serviceInstance.getService(); Set<ServiceUsageTypeDiscriminator> sutdSet = service.getServiceUsageTypeDiscriminator(); Long discriminatorId = 1L; for (ServiceUsageTypeDiscriminator sutd : sutdSet) { if (sutd.getDiscriminatorName().equalsIgnoreCase(discriminator)) { discriminatorId = sutd.getId(); break; } } String jsonString = "{conversionFactor: " + conversionFactor + ", operator: COMBINE, usageTypeId: " + serviceUsageTypeID; if (hasDiscriminator) { jsonString = jsonString + ", discriminatorVals: [ {discriminatorId: " + discriminatorId + ", discriminatorValue: 125, operator: EQUAL_TO, discriminatorValueName: " + discriminatorDisplayName + " } ]"; } jsonString = jsonString + " }"; org.json.JSONObject mediationJason = new org.json.JSONObject(jsonString); String productMediationRules = "[" + mediationJason.toString() + "]"; form.setProductMediationRules(productMediationRules); BindingResult result = validate(form); Product obtainedProduct = productsController.createProduct(form, result, map, response, request); Assert.assertNotNull(obtainedProduct); Assert.assertEquals(obtainedProduct.getName(), product.getName()); return obtainedProduct; }
From source file:com.gst.portfolio.shareaccounts.domain.ShareAccountCharge.java
private BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) { BigDecimal percentageOf = BigDecimal.ZERO; if (isGreaterThanZero(value)) { final MathContext mc = new MathContext(8, MoneyHelper.getRoundingMode()); final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); percentageOf = value.multiply(multiplicand, mc); }//from ww w. j a v a2 s .c o m return percentageOf; }
From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java
/** * Returns the DOWN rounded value of the given value for the given steps. * * @param value The original value to be rounded. * @param steps The steps./* w w w . j a va2 s . co m*/ * @return The DOWN rounded value of the given value for the given steps. */ public static BigDecimal roundDownTo(double value, double steps) { final BigDecimal bValue = BigDecimal.valueOf(value); final BigDecimal bSteps = BigDecimal.valueOf(steps); if (Objects.equals(bSteps, BigDecimal.ZERO)) { return bValue; } else { return bValue.divide(bSteps, 0, RoundingMode.FLOOR).multiply(bSteps); } }
From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java
private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying, Period[] expiries) {/* w w w .ja v a 2s . c o m*/ ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); } ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); String formattedName = MessageFormatter.format("[{}] {}", underlying, longName); ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (int i = 0; i < expiries.length; i++) { Period bucketPeriod = expiries[i]; ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1)); LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run LocalDate targetExpiry = nowish.plus(bucketPeriod); LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.warn("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] { chosenExpiry, bucketPeriod, targetExpiry }); Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (ExternalId optionTicker : tickersToLoad) { ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (Exception ex) { s_logger.error("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }
From source file:ca.sqlpower.matchmaker.munge.AddressCorrectionMungeStep.java
/** * Normalize addresses for deduping/*from w w w.j a va 2 s .co m*/ * @return */ private Boolean doCallNormalize() throws Exception { MungeStepOutput addressLine1MSO = getMSOInputs().get(0); String addressLine1 = (addressLine1MSO != null) ? (String) addressLine1MSO.getData() : null; MungeStepOutput addressLine2MSO = getMSOInputs().get(1); String addressLine2 = (addressLine2MSO != null) ? (String) addressLine2MSO.getData() : null; MungeStepOutput municipalityMSO = getMSOInputs().get(2); String municipality = (municipalityMSO != null) ? (String) municipalityMSO.getData() : null; MungeStepOutput provinceMSO = getMSOInputs().get(3); String province = (provinceMSO != null) ? (String) provinceMSO.getData() : null; MungeStepOutput countryMSO = getMSOInputs().get(4); String country = (countryMSO != null) ? (String) countryMSO.getData() : null; MungeStepOutput postalCodeMSO = getMSOInputs().get(5); String inPostalCode = (postalCodeMSO != null) ? (String) postalCodeMSO.getData() : null; // nicely formatted String addressString = addressLine1 + ", " + addressLine2 + ", " + municipality + ", " + province + ", " + inPostalCode + ", " + country; logger.debug("Parsing Address: " + addressString); Address address = Address.parse(addressLine1, municipality, province, inPostalCode, country, addressDB); logger.debug("Address that was parsed:\n" + address.toString()); AddressValidator validator = new AddressValidator(addressDB, address); validator.validate(); Address output; if (validator.getSuggestions().size() != 0 && validator.isValidSuggestion()) { output = validator.getSuggestions().get(0); logger.debug("Normalizing address to " + output); } else { output = address; } List<MungeStepOutput> outputs = getChildren(MungeStepOutput.class); outputs.get(0).setData(output.getAddress()); outputs.get(1).setData(addressLine2); outputs.get(2).setData(output.getSuite()); outputs.get(3) .setData(output.getStreetNumber() != null ? BigDecimal.valueOf(output.getStreetNumber()) : null); outputs.get(4).setData(output.getStreetNumberSuffix()); outputs.get(5).setData(output.getStreet()); outputs.get(6).setData(output.getStreetType()); outputs.get(7).setData(output.getStreetDirection()); outputs.get(8).setData(output.getMunicipality()); outputs.get(9).setData(output.getProvince()); outputs.get(10).setData(country); outputs.get(11).setData(output.getPostalCode()); outputs.get(12).setData(validator.isSerpValid()); return true; }
From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java
private StockProduct syncProduct(StockProduct stockProduct, StockQuote quote) { stockProduct.setHigh(BigDecimal.valueOf(quote.getHigh())); stockProduct.setLow(BigDecimal.valueOf(quote.getLow())); stockProduct.setDailyLatestChange(BigDecimal.valueOf(quote.getLastChange())); stockProduct.setDailyLatestChangePercent(BigDecimal.valueOf(quote.getLastChangePercent())); stockProduct.setDailyLatestValue(BigDecimal.valueOf(quote.getLast())); stockProduct.setPreviousClose(BigDecimal.valueOf(quote.getPreviousClose())); stockProduct.setOpen(BigDecimal.valueOf(quote.getOpen())); if (!StringUtils.isEmpty(quote.getExchange())) { stockProduct.setExchange(exchangeService.get(quote.getExchange())); }//from w w w.ja v a 2 s .c o m if (!StringUtils.isEmpty(quote.getCurrency())) { stockProduct.setCurrency(quote.getCurrency()); } stockProduct.setQuote(quote); return stockProduct; }
From source file:org.kuali.coeus.s2sgen.impl.generate.support.NASAOtherProjectInformationV1_0Generator.java
/** * // www . ja v a 2 s . co m * This method gives information of NasaCivilServicePersonnel for * NasaOtherProjectInformation * * @return NASACivilServicePersonnel object containing Nasa civil service * personnel details. */ private NASACivilServicePersonnel getNasaCivilServicePersonnel() { NASACivilServicePersonnel nasaCivilServicePersonnel = NASACivilServicePersonnel.Factory.newInstance(); String answerDetails = getAnswer(CIVIL_SERVICE_PERSONNEL, answerHeaders); if (answerDetails != null && !answerDetails.equals(NOT_ANSWERED)) { YesNoDataType.Enum answer = (answerDetails.equals(YnqConstant.YES.code()) ? YesNoDataType.Y_YES : YesNoDataType.N_NO); nasaCivilServicePersonnel.setCivilServicePersonnel(answer); } List<String> fteAnswerDetails = getAnswerList(FTE); List<String> fiscalYearDetails = getAnswerList(FISCAL_YEAR); if (fteAnswerDetails.size() > FISCAL_YEAR_1) { FYFTE1 fyfte1 = FYFTE1.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_1); BigDecimal fte1 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte1.setFTE1(fte1); if (fiscalYearDetails.size() > FISCAL_YEAR_1) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_1); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte1.setFY1(fyscalYear); nasaCivilServicePersonnel.setFYFTE1(fyfte1); } } else if (answerDetails != null && answerDetails.equals(YnqConstant.YES.code())) { nasaCivilServicePersonnel.setFYFTE1(null); } if (fteAnswerDetails.size() > FISCAL_YEAR_2) { FYFTE2 fyfte2 = FYFTE2.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_2); BigDecimal fte2 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte2.setFTE2(fte2); if (fiscalYearDetails.size() > FISCAL_YEAR_2) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_2); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte2.setFY2(fyscalYear); nasaCivilServicePersonnel.setFYFTE2(fyfte2); } } if (fteAnswerDetails.size() > FISCAL_YEAR_3) { FYFTE3 fyfte3 = FYFTE3.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_3); BigDecimal fte3 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte3.setFTE3(fte3); if (fiscalYearDetails.size() > FISCAL_YEAR_3) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_3); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte3.setFY3(fyscalYear); nasaCivilServicePersonnel.setFYFTE3(fyfte3); } } if (fteAnswerDetails.size() > FISCAL_YEAR_4) { FYFTE4 fyfte4 = FYFTE4.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_4); BigDecimal fte4 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte4.setFTE4(fte4); if (fiscalYearDetails.size() > FISCAL_YEAR_4) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_4); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte4.setFY4(fyscalYear); nasaCivilServicePersonnel.setFYFTE4(fyfte4); } } if (fteAnswerDetails.size() > FISCAL_YEAR_5) { FYFTE5 fyfte5 = FYFTE5.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_5); BigDecimal fte5 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte5.setFTE5(fte5); if (fiscalYearDetails.size() > FISCAL_YEAR_5) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_5); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte5.setFY5(fyscalYear); nasaCivilServicePersonnel.setFYFTE5(fyfte5); } } if (fteAnswerDetails.size() > FISCAL_YEAR_6) { FYFTE6 fyfte6 = FYFTE6.Factory.newInstance(); String fte = fteAnswerDetails.get(FISCAL_YEAR_6); BigDecimal fte6 = BigDecimal.valueOf(Double.parseDouble(fte)); fyfte6.setFTE6(fte6); if (fiscalYearDetails.size() > FISCAL_YEAR_6) { String fiscalYear = fiscalYearDetails.get(FISCAL_YEAR_6); FYDataType.Enum fyscalYear = getFisaclYear(fiscalYear); fyfte6.setFY6(fyscalYear); nasaCivilServicePersonnel.setFYFTE6(fyfte6); } } if (fteAnswerDetails.size() != fiscalYearDetails.size()) { nasaCivilServicePersonnel.setFYFTE1(null); } return nasaCivilServicePersonnel; }
From source file:net.sourceforge.fenixedu.domain.studentCurriculum.CycleCurriculumGroup.java
final public BigDecimal getAverage(final ExecutionYear executionYear) { return executionYear == null && isConcluded() && isConclusionProcessed() ? BigDecimal.valueOf(getFinalAverage()) : getCurriculum(new DateTime(), executionYear).getAverage(); }
From source file:com.att.aro.core.videoanalysis.impl.BufferInSecondsCalculatorImpl.java
public double drawVeWithIn(List<VideoEvent> veWithIn, double beginBuffer) { double buffer = beginBuffer; if (veWithIn.size() == 0 && completedDownloads.contains(chunkPlaying)) { buffer = bufferDrain(buffer);//ww w .j a v a 2 s . c o m } else if (completedDownloads.contains(chunkPlaying)) { Collections.sort(veWithIn, new VideoEventComparator(SortSelection.END_TS)); boolean drained = false; VideoEvent chunk; double timeRange; double durationLeft = chunkPlayTimeDuration; seriesDataSets.put(key, chunkPlayStartTime + "," + buffer); key++; if (stallStarted) { updateStallInformation(chunkPlayStartTime); stallStarted = false; } for (int index = 0; index < veWithIn.size(); index++) { chunk = veWithIn.get(index); if (MathUtils.equals(chunk.getEndTS(), chunkPlayEndTime)) { // finish draining buffer = buffer - durationLeft; if (buffer <= 0) { buffer = 0; updateStallInformation(chunk.getEndTS()); } seriesDataSets.put(key, chunkPlayEndTime + "," + buffer); key++; drained = true; buffer = buffer + getChunkPlayTimeDuration(chunk); seriesDataSets.put(key, chunk.getEndTS() + "," + buffer); key++; completedDownloads.add(chunk); chunkDownload.remove(chunk); } else { if (index == 0) { timeRange = chunk.getEndTS() - chunkPlayStartTime; } else { timeRange = chunk.getEndTS() - veWithIn.get(index - 1).getEndTS(); } buffer = buffer - timeRange; if (buffer <= 0) { buffer = 0; stallStarted = true; updateStallInformation(chunk.getEndTS()); } durationLeft = durationLeft - timeRange; seriesDataSets.put(key, chunk.getEndTS() + "," + buffer); key++; buffer = buffer + getChunkPlayTimeDuration(chunk); seriesDataSets.put(key, chunk.getEndTS() + "," + buffer); key++; completedDownloads.add(chunk); chunkDownload.remove(chunk); } } if (drained == false) { buffer = buffer - durationLeft; if (buffer <= 0) { buffer = 0; stallStarted = true; updateStallInformation(chunkPlayEndTime); } seriesDataSets.put(key, chunkPlayEndTime + "," + buffer); key++; } } else { boolean skipStallStart = false; for (VideoStall stall : videoStallResult) { if (BigDecimal.valueOf(stall.getStallStartTimeStamp()) == BigDecimal.valueOf(chunkPlayStartTime)) { skipStallStart = true; break; } } if (skipStallStart == false) { stallStarted = true; VideoStall stall = new VideoStall(chunkPlayStartTime); videoStallResult.add(stall); } return -1; } return buffer; }
From source file:org.mongojack.internal.object.BsonObjectTraversingParser.java
@Override public BigDecimal getDecimalValue() throws IOException { Number n = currentNumericNode(); if (n instanceof BigDecimal) { return (BigDecimal) n; } else {//from w w w. j av a 2s . c o m return BigDecimal.valueOf(n.doubleValue()); } }