List of usage examples for java.math BigDecimal setScale
@Deprecated(since = "9") public BigDecimal setScale(int newScale, int roundingMode)
From source file:org.globus.exec.client.HackedGramJob.java
private EndpointReferenceType createJobEndpoint(final ManagedJobFactoryPortType factoryPort, final boolean batch) throws Exception { // Create a service instance base on creation info logger.debug("creating ManagedJob instance"); if (logger.isDebugEnabled()) { long millis = System.currentTimeMillis(); BigDecimal seconds = new BigDecimal(((double) millis) / 1000); seconds = seconds.setScale(3, BigDecimal.ROUND_HALF_DOWN); logger.debug("submission time, in seconds from the Epoch:" + "\nbefore: " + seconds.toString()); logger.debug("\nbefore, in milliseconds: " + millis); }// w w w . jav a 2s . c om ((org.apache.axis.client.Stub) factoryPort).setTimeout(this.axisStubTimeOut); CreateManagedJobInputType jobInput = new CreateManagedJobInputType(); jobInput.setInitialTerminationTime(getTerminationTime()); if (this.id != null) { jobInput.setJobID(new AttributedURI(this.id)); } if (this.jobDescription instanceof MultiJobDescriptionType) { jobInput.setMultiJob((MultiJobDescriptionType) this.getDescription()); } else { jobInput.setJob(this.getDescription()); } if (!batch) { if (this.useDefaultNotificationConsumer) { setupNotificationConsumerManager(); } try { if (this.useDefaultNotificationConsumer) { setupNotificationConsumer(); } Subscribe subscriptionRequest = new Subscribe(); subscriptionRequest.setConsumerReference(this.notificationConsumerEPR); TopicExpressionType topicExpression = new TopicExpressionType(WSNConstants.SIMPLE_TOPIC_DIALECT, ManagedJobConstants.RP_STATE); subscriptionRequest.setTopicExpression(topicExpression); jobInput.setSubscribe(subscriptionRequest); } catch (Exception e) { // may happen...? Let's not fail. logger.error(e); try { unbind(); } catch (Exception unbindEx) { // let's not fail the unbinding logger.error(unbindEx); } } } if (logger.isInfoEnabled()) { logger.info("<startTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</startTime>"); } CreateManagedJobOutputType response = factoryPort.createManagedJob(jobInput); if (logger.isInfoEnabled()) { logger.info("<endTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</endTime"); } EndpointReferenceType jobEPR = (EndpointReferenceType) ObjectSerializer .clone(response.getManagedJobEndpoint()); // This doesn't work with GRAM.NET for some reason... /* if(logger.isDebugEnabled()) { * logger.debug("Job Handle: " + AuditUtil.eprToGridId(jobEPR)); Element jobEndpointElement = null; try { jobEndpointElement = ObjectSerializer.toElement( jobEPR, new QName( "http://schemas.xmlsoap.org/ws/2004/03/addressing", "EndpointReferenceType")); } catch (Exception e) * { throw new RuntimeException(e); } logger.debug("Job EPR: " + XmlUtils.toString(jobEndpointElement)); } */ EndpointReferenceType subscriptionEPR = response.getSubscriptionEndpoint(); if (subscriptionEPR != null) { this.notificationProducerEPR = (EndpointReferenceType) ObjectSerializer.clone(subscriptionEPR); } if (logger.isDebugEnabled()) { Calendar terminationTime = response.getNewTerminationTime(); Calendar serviceCurrentTime = response.getCurrentTime(); logger.debug( "Termination time granted by the factory to the job resource: " + terminationTime.getTime()); logger.debug("Current time seen by the factory service on creation: " + serviceCurrentTime.getTime()); } return jobEPR; }
From source file:com.photon.phresco.framework.commons.FrameworkUtil.java
public static float roundFloat(int decimal, double value) { BigDecimal roundThroughPut = new BigDecimal(value); return roundThroughPut.setScale(decimal, BigDecimal.ROUND_HALF_EVEN).floatValue(); }
From source file:com.salesmanager.core.util.ProductUtil.java
public static String formatHTMLProductPrice(Locale locale, String currency, Product view, boolean showDiscountDate, boolean shortDiscountFormat) { if (currency == null) { log.error("Currency is null ..."); return "-N/A-"; }// w ww. j a v a2 s . c o m int decimalPlace = 2; String prefix = ""; String suffix = ""; Map currenciesmap = RefCache.getCurrenciesListWithCodes(); Currency c = (Currency) currenciesmap.get(currency); // regular price BigDecimal bdprodprice = view.getProductPrice(); Date dt = new Date(); // discount price java.util.Date spdate = null; java.util.Date spenddate = null; BigDecimal bddiscountprice = null; Special special = view.getSpecial(); if (special != null) { spdate = special.getSpecialDateAvailable(); spenddate = special.getExpiresDate(); if (spdate.before(new Date(dt.getTime())) && spenddate.after(new Date(dt.getTime()))) { bddiscountprice = special.getSpecialNewProductPrice(); } } // all other prices Set prices = view.getPrices(); if (prices != null) { Iterator pit = prices.iterator(); while (pit.hasNext()) { ProductPrice pprice = (ProductPrice) pit.next(); if (pprice.isDefaultPrice()) { pprice.setLocale(locale); suffix = pprice.getPriceSuffix(); bddiscountprice = null; spdate = null; spenddate = null; bdprodprice = pprice.getProductPriceAmount(); ProductPriceSpecial ppspecial = pprice.getSpecial(); if (ppspecial != null) { if (ppspecial.getProductPriceSpecialStartDate() != null && ppspecial.getProductPriceSpecialEndDate() != null) { spdate = ppspecial.getProductPriceSpecialStartDate(); spenddate = ppspecial.getProductPriceSpecialEndDate(); } bddiscountprice = ppspecial.getProductPriceSpecialAmount(); } break; } } } double fprodprice = 0; ; if (bdprodprice != null) { fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue(); } // regular price String String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency); // discount price String String discountprice = null; String savediscount = null; if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime())) && spenddate.after(new Date(dt.getTime())))) { double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue(); discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency); double arith = fdiscountprice / fprodprice; double fsdiscount = 100 - arith * 100; Float percentagediscount = new Float(fsdiscount); savediscount = String.valueOf(percentagediscount.intValue()); } StringBuffer p = new StringBuffer(); p.append("<div class='product-price'>"); if (discountprice == null) { p.append("<div class='product-price-price' style='width:50%;float:left;'>"); p.append(regularprice); if (!StringUtils.isBlank(suffix)) { p.append(suffix).append(" "); } p.append("</div>"); p.append("<div class='product-line'> </div>"); } else { p.append("<div style='width:50%;float:left;'>"); p.append("<strike>").append(regularprice); if (!StringUtils.isBlank(suffix)) { p.append(suffix).append(" "); } p.append("</strike>"); p.append("</div>"); p.append("<div style='width:50%;float:right;'>"); p.append("<font color='red'>").append(discountprice); if (!StringUtils.isBlank(suffix)) { p.append(suffix).append(" "); } p.append("</font>"); if (!shortDiscountFormat) { p.append("<br>").append("<font color='red' style='font-size:75%;'>") .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ") .append(savediscount) .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ") .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>"); } if (showDiscountDate && spenddate != null) { p.append("<br>").append(" <font style='font-size:65%;'>") .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append(" ") .append(DateUtil.formatDate(spenddate)).append("</font>"); } p.append("</div>").toString(); } p.append("</div>"); return p.toString(); }
From source file:com.salesmanager.core.util.ProductUtil.java
public static BigDecimal determinePrice(Product product, Locale locale, String currency) { int decimalPlace = 2; Map currenciesmap = RefCache.getCurrenciesListWithCodes(); Currency c = (Currency) currenciesmap.get(currency); // prices//from ww w . j a v a2 s . c om BigDecimal bdprodprice = product.getProductPrice(); BigDecimal bddiscountprice = null; // discount price Special special = product.getSpecial(); java.util.Date spdate = null; java.util.Date spenddate = null; if (special != null) { bddiscountprice = special.getSpecialNewProductPrice(); spdate = special.getSpecialDateAvailable(); spenddate = special.getExpiresDate(); } Date dt = new Date(); // all other prices Set prices = product.getPrices(); if (prices != null) { Iterator pit = prices.iterator(); while (pit.hasNext()) { ProductPrice pprice = (ProductPrice) pit.next(); pprice.setLocale(locale); if (pprice.isDefaultPrice()) {// overwrites default price bddiscountprice = null; spdate = null; spenddate = null; bdprodprice = pprice.getProductPriceAmount(); ProductPriceSpecial ppspecial = pprice.getSpecial(); if (ppspecial != null) { if (ppspecial.getProductPriceSpecialStartDate() != null && ppspecial.getProductPriceSpecialEndDate() != null && ppspecial.getProductPriceSpecialStartDate().before(new Date(dt.getTime())) && ppspecial.getProductPriceSpecialEndDate().after(new Date(dt.getTime()))) { bddiscountprice = ppspecial.getProductPriceSpecialAmount(); } else if (ppspecial.getProductPriceSpecialDurationDays() > -1) { bddiscountprice = ppspecial.getProductPriceSpecialAmount(); } } break; } } } double fprodprice = 0; if (bdprodprice != null) { fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue(); } if (bddiscountprice != null) { return bddiscountprice; } else { return bdprodprice; } }
From source file:net.sourceforge.fenixedu.domain.Teacher.java
public BigDecimal getProjectsTutorialsCredits(ExecutionYear executionYear) { BigDecimal result = BigDecimal.ZERO; for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) { TeacherService teacherService = getTeacherServiceByExecutionPeriod(executionSemester); if (teacherService != null) { for (DegreeProjectTutorialService degreeProjectTutorialService : teacherService .getDegreeProjectTutorialServices()) { result = result.add(degreeProjectTutorialService.getDegreeProjectTutorialServiceCredits()); }//from w w w . j a v a2s . c om } } return result.setScale(2, BigDecimal.ROUND_HALF_UP); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.directiveCouncil.SummariesControlAction.java
private List<DetailSummaryElement> getExecutionCourseResume(final ExecutionSemester executionSemester, Collection<Professorship> professorships) { List<DetailSummaryElement> allListElements = new ArrayList<DetailSummaryElement>(); LocalDate today = new LocalDate(); LocalDate oneWeekBeforeToday = today.minusDays(8); for (Professorship professorship : professorships) { BigDecimal summariesGiven = EMPTY, lessonsDeclared = EMPTY; BigDecimal givenSumariesPercentage = EMPTY; BigDecimal notTaughtSummaries = EMPTY; BigDecimal notTaughtSummariesPercentage = EMPTY; if (professorship.belongsToExecutionPeriod(executionSemester) && !professorship.getExecutionCourse().isMasterDegreeDFAOrDEAOnly()) { for (Shift shift : professorship.getExecutionCourse().getAssociatedShifts()) { DegreeTeachingService degreeTeachingService = professorship .getDegreeTeachingServiceByShift(shift); if (degreeTeachingService != null) { // Get the number of declared lessons lessonsDeclared = getDeclaredLesson(degreeTeachingService.getPercentage(), shift, lessonsDeclared, oneWeekBeforeToday); }/* w ww.j a v a 2s. co m*/ // Get the number of summaries given summariesGiven = getSummariesGiven(professorship, shift, summariesGiven, oneWeekBeforeToday); // Get the number of not taught summaries notTaughtSummaries = getNotTaughtSummaries(professorship, shift, notTaughtSummaries, oneWeekBeforeToday); } summariesGiven = summariesGiven.setScale(1, RoundingMode.HALF_UP); notTaughtSummaries = notTaughtSummaries.setScale(1, RoundingMode.HALF_UP); lessonsDeclared = lessonsDeclared.setScale(1, RoundingMode.HALF_UP); givenSumariesPercentage = getDifference(lessonsDeclared, summariesGiven); notTaughtSummariesPercentage = getDifference(lessonsDeclared, notTaughtSummaries); Teacher teacher = professorship.getTeacher(); String categoryName = teacher != null && teacher.getCategory() != null ? teacher.getCategory().getName().getContent() : null; String siglas = getSiglas(professorship); String teacherEmail = professorship.getPerson().getDefaultEmailAddress() != null ? professorship.getPerson().getDefaultEmailAddress().getPresentationValue() : null; DetailSummaryElement listElementDTO = new DetailSummaryElement(professorship.getPerson().getName(), professorship.getExecutionCourse().getNome(), teacher != null ? teacher.getTeacherId() : null, teacherEmail, categoryName, lessonsDeclared, summariesGiven, givenSumariesPercentage, notTaughtSummaries, notTaughtSummariesPercentage, siglas); allListElements.add(listElementDTO); } } return allListElements; }
From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
/** * @see org.kuali.ole.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.ole.module.purap.document.PaymentRequestDocument) *///from ww w. j a va2 s . c o m @Override public void convertMoneyToPercent(PaymentRequestDocument pr) { LOG.debug("convertMoneyToPercent() started"); int itemNbr = 0; for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) { PaymentRequestItem item = iter.next(); itemNbr++; String identifier = item.getItemIdentifierString(); if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) { int numOfAccounts = item.getSourceAccountingLines().size(); BigDecimal percentTotal = BigDecimal.ZERO; KualiDecimal accountTotal = KualiDecimal.ZERO; int accountIdentifier = 0; KualiDecimal addChargeItem = KualiDecimal.ZERO; KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO; /* KualiDecimal prorateSurcharge = KualiDecimal.ZERO; if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) { if (((OlePaymentRequestItem) item).getItemSurcharge() != null) { prorateSurcharge = new KualiDecimal(((OlePaymentRequestItem) item).getItemSurcharge()).multiply(item.getItemQuantity()); } }*/ PurApAccountingLine lastAccount = null; BigDecimal accountTotalPercent = BigDecimal.ZERO; for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) { accountIdentifier++; PaymentRequestAccount account = (PaymentRequestAccount) purApAccountingLine; // account.getAmount returns the wrong value for trade in source accounting lines... KualiDecimal accountAmount = KualiDecimal.ZERO; if (ObjectUtils.isNotNull(account.getAmount())) { accountAmount = account.getAmount(); } BigDecimal tmpPercent = BigDecimal.ZERO; KualiDecimal extendedPrice = item.getTotalAmount(); tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(), PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR); if (accountIdentifier == numOfAccounts) { // if on last account, calculate the percent by subtracting current percent total from 1 tmpPercent = BigDecimal.ONE.subtract(percentTotal); } // test that the above amount is correct, if so just check that the total of all these matches the item total BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue()); calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR); KualiDecimal calcAmount = new KualiDecimal(calcAmountBd); //calcAmount = calcAmount.subtract(prorateSurcharge); if (calcAmount.compareTo(accountAmount) != 0) { // rounding error if (LOG.isDebugEnabled()) { LOG.debug("convertMoneyToPercent() Rounding error on " + account); } String param1 = identifier + "." + accountIdentifier; String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue()) .toString(); GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(), PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2); account.setAmount(calcAmount); } // update percent if (LOG.isDebugEnabled()) { LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent); } account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100))); accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent()); lastAccount = account; // check total based on adjusted amount accountTotal = accountTotal.add(calcAmount); percentTotal = percentTotal.add(tmpPercent); } BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent) .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING); if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) { KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent)) .subtract(new KualiDecimal(100))).abs()); if ((differencePercent.abs()).isLessEqual( new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size()) .divide(new KualiDecimal(2)))))) { lastAccount .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference)); } else { lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent()); } } } } }
From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
@Override public void convertMoneyToPercent(InvoiceDocument inv) { LOG.debug("convertMoneyToPercent() started"); int itemNbr = 0; for (Iterator<InvoiceItem> iter = inv.getItems().iterator(); iter.hasNext();) { InvoiceItem item = iter.next();//from w w w . j a v a2s.co m itemNbr++; String identifier = item.getItemIdentifierString(); if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) { int numOfAccounts = item.getSourceAccountingLines().size(); BigDecimal percentTotal = BigDecimal.ZERO; KualiDecimal accountTotal = KualiDecimal.ZERO; int accountIdentifier = 0; KualiDecimal addChargeItem = KualiDecimal.ZERO; KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO; KualiDecimal prorateSurcharge = KualiDecimal.ZERO; if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) { if (((OleInvoiceItem) item).getItemSurcharge() != null) { prorateSurcharge = new KualiDecimal(((OleInvoiceItem) item).getItemSurcharge()) .multiply(item.getItemQuantity()); } } PurApAccountingLine lastAccount = null; BigDecimal accountTotalPercent = BigDecimal.ZERO; for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) { accountIdentifier++; InvoiceAccount account = (InvoiceAccount) purApAccountingLine; // account.getAmount returns the wrong value for trade in source accounting lines... KualiDecimal accountAmount = KualiDecimal.ZERO; if (ObjectUtils.isNotNull(account.getAmount())) { accountAmount = account.getAmount(); } BigDecimal tmpPercent = BigDecimal.ZERO; KualiDecimal extendedPrice = item.getTotalAmount(); tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(), PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR); if (accountIdentifier == numOfAccounts) { // if on last account, calculate the percent by subtracting current percent total from 1 tmpPercent = BigDecimal.ONE.subtract(percentTotal); } // test that the above amount is correct, if so just check that the total of all these matches the item total BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue()); calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR); KualiDecimal calcAmount = new KualiDecimal(calcAmountBd); calcAmount = calcAmount.subtract(prorateSurcharge); if (calcAmount.compareTo(accountAmount) != 0) { // rounding error if (LOG.isDebugEnabled()) { LOG.debug("convertMoneyToPercent() Rounding error on " + account); } String param1 = identifier + "." + accountIdentifier; String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue()) .toString(); GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(), PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2); account.setAmount(calcAmount); } // update percent if (LOG.isDebugEnabled()) { LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent); } account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100))); accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent()); lastAccount = account; // check total based on adjusted amount accountTotal = accountTotal.add(calcAmount); percentTotal = percentTotal.add(tmpPercent); } BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent) .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING); if (ObjectUtils.isNotNull(lastAccount) && ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) { KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent)) .subtract(new KualiDecimal(100))).abs()); if ((differencePercent.abs()).isLessEqual( new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size()) .divide(new KualiDecimal(2)))))) { lastAccount .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference)); } else { lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent()); } } } } }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
private void prepareCollectionIndexDetails(final WaterChargeDashBoardResponse collectionIndexDetails, final BigDecimal totalDemand, final int noOfMonths) { final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails/*from ww w . java 2 s . c o m*/ .setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP)); // performance = (current year tilldate collection * 100)/(proportional // demand) if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails.setPerformance( collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); // variance = ((currentYearCollection - // lastYearCollection)*100)/lastYearCollection BigDecimal variation; if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else variation = collectionIndexDetails.getCurrentYearTillDateColl() .subtract(collectionIndexDetails.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); collectionIndexDetails.setLastYearVar(variation); }
From source file:br.com.fidias.chance4j.Chance.java
/** * Return a random BigDecimal number./*w w w. j a v a 2 s . co m*/ * <pre> * chance.getBigDecimal(-10, 100, 2); * => 45.89 * </pre> * * @param min Minimum value to choose from * @param max Maximum value to choose from * @param fixed Specify a fixed precision * @return A random BigDecimal * @throws ChanceException */ public BigDecimal getBigDecimal(Integer min, Integer max, int fixed) throws ChanceException { if (min != null && max != null && max < min) { throw new ChanceException("Max must be greater than min."); } int num; int localFixed = (int) Math.pow(10, fixed + FORCE_INCREASE_FIXED); int localMax = (int) (Integer.MAX_VALUE / localFixed); int localMin = -localMax; if (max == null) { max = localMax; } else if (max > localMax) { final String message = "Max specified (%d) is out of range with fixed. " + "Max should be, at most, %d"; throw new ChanceException(String.format(message, max, localMax)); } if (min == null) { min = localMin; } else if (min < localMin) { final String message = "Min specified (%d) is out of range with fixed. " + "Min should be, at least, %d"; throw new ChanceException(String.format(message, min, localMin)); } num = integer(min * localFixed, max * localFixed); BigDecimal bd = new BigDecimal(num).divide(new BigDecimal(localFixed), MathContext.UNLIMITED); return bd.setScale(fixed, RoundingMode.UP); }