List of usage examples for java.math BigDecimal setScale
@Deprecated(since = "9") public BigDecimal setScale(int newScale, int roundingMode)
From source file:org.cgiar.ccafs.marlo.action.projects.ProjectBudgetByFlagshipAction.java
/** * Roun up the value that the user put in the value field * /* w w w . jav a 2 s. c o m*/ * @param value * @param places * @return round number value */ public double round(double value, int places) { if (places < 0) { throw new IllegalArgumentException(); } BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
From source file:com.salesmanager.catalog.product.ProductDetailsAction.java
public String createReview() { try {// ww w.j a va2 s . c o m MerchantStore store = SessionUtil.getMerchantStore(super.getServletRequest()); // requires Customer Customer customer = SessionUtil.getCustomer(super.getServletRequest()); if (customer == null) { super.setMessage("message.review.loggedin"); return INPUT; } // product details CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService); product = cservice.getProduct(this.getProduct().getProductId()); product.setLocale(super.getLocale()); // create review // check text if (StringUtils.isBlank(this.getReviewText()) || StringUtils.isBlank(this.getReviewText())) { super.setErrorMessage("error.messag.review"); return INPUT; } Review r = new Review(); r.setCustomerId(customer.getCustomerId()); r.setCustomerName(customer.getName()); r.setDateAdded(new Date()); r.setLastModified(new Date()); r.setProductId(product.getProductId()); r.setProductName(product.getName()); r.setReviewRating(this.getRating()); r.setLocale(super.getLocale()); ReviewDescription description = new ReviewDescription(); description.setReviewText(this.getReviewText()); Set s = new HashSet(); s.add(description); r.setDescriptions(s); cservice.addProductReview(store, r); counter = cservice.countAverageRatingPerProduct(this.getProduct().getProductId()); if (counter != null) { double average = counter.getAverage(); BigDecimal bdaverage = new BigDecimal(average); bdaverage.setScale(2, BigDecimal.ROUND_HALF_EVEN); product.setProductReviewCount(counter.getCount()); product.setProductReviewAvg(bdaverage); cservice.saveOrUpdateProduct(product); } super.setMessage("message.review.created"); } catch (Exception e) { logger.error(e); super.setTechnicalMessage(); return INPUT; } return SUCCESS; }
From source file:org.kuali.kfs.fp.document.service.impl.BudgetAdjustmentLaborBenefitsServiceImpl.java
/** * Given a budget adjustment accounting line, generates appropriate fringe benefit lines for the line * * @param line a line to generate fringe benefit lines for * @return a List of BudgetAdjustmentAccountingLines to add to the document as fringe benefit lines *//*from w ww.j av a2 s .c o m*/ protected List<BudgetAdjustmentAccountingLine> generateBenefitLines(Integer fiscalYear, BudgetAdjustmentAccountingLine line, BudgetAdjustmentDocument document) { List<BudgetAdjustmentAccountingLine> fringeLines = new ArrayList<BudgetAdjustmentAccountingLine>(); try { Collection<LaborLedgerPositionObjectBenefit> objectBenefits = SpringContext .getBean(LaborModuleService.class).retrieveActiveLaborPositionObjectBenefits(fiscalYear, line.getChartOfAccountsCode(), line.getFinancialObjectCode()); if (objectBenefits != null) { for (LaborLedgerPositionObjectBenefit fringeBenefitInformation : objectBenefits) { // now create and set properties for the benefit line BudgetAdjustmentAccountingLine benefitLine = null; if (line.isSourceAccountingLine()) { benefitLine = (BudgetAdjustmentAccountingLine) document.getSourceAccountingLineClass() .newInstance(); } else { benefitLine = (BudgetAdjustmentAccountingLine) document.getTargetAccountingLineClass() .newInstance(); } // create a map to use in the lookup of the account Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("chartOfAccountsCode", line.getChartOfAccountsCode()); fieldValues.put("accountNumber", line.getAccountNumber()); // use the budget adjustment accounting line to get the account number that will then be used to lookup the // labor benefit rate category code Account lookupAccount = businessObjectService.findByPrimaryKey(Account.class, fieldValues); LaborLedgerBenefitsCalculation benefitsCalculation = null; String laborBenefitsRateCategoryCode = ""; // make sure the parameter exists if (SpringContext.getBean(ParameterService.class).parameterExists(Account.class, KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE)) { laborBenefitsRateCategoryCode = SpringContext.getBean(ParameterService.class) .getParameterValueAsString(Account.class, KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE); } else { laborBenefitsRateCategoryCode = ""; } // make sure the system parameter exists if (SpringContext.getBean(ParameterService.class).parameterExists( KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND)) { // check the system param to see if the labor benefit rate category should be filled in String sysParam = SpringContext.getBean(ParameterService.class).getParameterValueAsString( KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND); LOG.debug("sysParam: " + sysParam); // if sysParam == Y then Labor Benefit Rate Category should be used in the search if (sysParam.equalsIgnoreCase("Y")) { if (StringUtils.isBlank(line.getSubAccount().getSubAccountNumber())) { laborBenefitsRateCategoryCode = lookupAccount.getLaborBenefitRateCategoryCode(); } else { laborBenefitsRateCategoryCode = SpringContext.getBean(LaborModuleService.class) .getBenefitRateCategoryCode(line.getChartOfAccountsCode(), line.getAccountNumber(), line.getSubAccount().getSubAccountNumber()); } // make sure laborBenefitsRateCategoryCode isn't null if (ObjectUtils.isNull(laborBenefitsRateCategoryCode)) { // make sure the parameter exists if (SpringContext.getBean(ParameterService.class).parameterExists(Account.class, KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE)) { laborBenefitsRateCategoryCode = SpringContext.getBean(ParameterService.class) .getParameterValueAsString(Account.class, KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE); } else { laborBenefitsRateCategoryCode = ""; } } } } String beneCalc = "{" + fringeBenefitInformation.getUniversityFiscalYear() + "," + fringeBenefitInformation.getChartOfAccountsCode() + "," + fringeBenefitInformation.getFinancialObjectBenefitsTypeCode() + "," + laborBenefitsRateCategoryCode + "}"; LOG.info("Looking for a benefits calculation for " + beneCalc); // get the benefits calculation taking the laborBenefitRateCategoryCode into account benefitsCalculation = fringeBenefitInformation .getLaborLedgerBenefitsCalculation(laborBenefitsRateCategoryCode); if (benefitsCalculation != null) { LOG.info("Found benefits calculation for " + beneCalc); } else { LOG.info("Couldn't locate a benefits calculation for " + beneCalc); } if ((benefitsCalculation != null) && benefitsCalculation.isActive()) { benefitLine.copyFrom(line); benefitLine .setFinancialObjectCode(benefitsCalculation.getPositionFringeBenefitObjectCode()); benefitLine.refreshNonUpdateableReferences(); LaborModuleService laborModuleService = SpringContext.getBean(LaborModuleService.class); if (ObjectUtils.isNotNull(laborModuleService.getCostSharingSourceAccountNumber())) { benefitLine.setAccountNumber(laborModuleService.getCostSharingSourceAccountNumber()); benefitLine .setSubAccountNumber(laborModuleService.getCostSharingSourceSubAccountNumber()); benefitLine.setChartOfAccountsCode( laborModuleService.getCostSharingSourceChartOfAccountsCode()); } benefitLine.refreshNonUpdateableReferences(); // convert whole percentage to decimal value (5% to .0500, 18.66% to 0.1866) BigDecimal fringeBenefitPercent = formatPercentageForMultiplication( benefitsCalculation.getPositionFringeBenefitPercent()); // compute the benefit current amount with all decimals and then round it to the closest integer by setting the // scale to 0 and using the round half up rounding mode: exp. 1200*0.1866 = 223.92 -> rounded to 224 BigDecimal benefitCurrentAmount = line.getCurrentBudgetAdjustmentAmount().bigDecimalValue() .multiply(fringeBenefitPercent); benefitCurrentAmount = benefitCurrentAmount.setScale(2, BigDecimal.ROUND_HALF_UP); benefitLine.setCurrentBudgetAdjustmentAmount(new KualiDecimal(benefitCurrentAmount)); KualiInteger benefitBaseAmount = line.getBaseBudgetAdjustmentAmount() .multiply(fringeBenefitPercent); benefitLine.setBaseBudgetAdjustmentAmount(benefitBaseAmount); // clear monthly lines per KULEDOCS-1606 benefitLine.clearFinancialDocumentMonthLineAmounts(); // set flag on line so we know it was a generated benefit line and can clear it out later if needed benefitLine.setFringeBenefitIndicator(true); fringeLines.add(benefitLine); } } } } catch (InstantiationException ie) { // it's doubtful this catch block or the catch block below are ever accessible, as accounting lines should already have // been generated // for the document. But we can still make it somebody else's problem throw new RuntimeException(ie); } catch (IllegalAccessException iae) { // with some luck we'll pass the buck now sez some other dev "This sucks!" Get your Runtime on! // but really...we'll never make it this far. I promise. throw new RuntimeException(iae); } return fringeLines; }
From source file:org.egov.ptis.repository.dashboard.RevenueDashboardRepository.java
public List<Map<String, Object>> getRevenueZonewisePerformance() { final List<Object[]> overallData = getQuery("revenue.ptis.zonewise.overall.performance").list(); final Map<String, Map<String, Object>> revenueDataHolder = new HashMap<String, Map<String, Object>>(); for (final Object[] revenueObj : overallData) { final Map<String, Object> revnData = new HashMap<String, Object>(); revnData.put("zone", String.valueOf(revenueObj[0])); final BigDecimal collectionPerc = (BigDecimal) revenueObj[1]; revnData.put("collectionPerc", collectionPerc != null ? collectionPerc.doubleValue() : "0"); revenueDataHolder.put(String.valueOf(revenueObj[0]), revnData); }//from w w w .j av a 2 s . c om final List<Object[]> monthlyData = getQuery("revenue.ptis.zonewise.monthly.performance").list(); for (final Object[] revenuData : monthlyData) { final Map<String, Object> revnData = revenueDataHolder.get(String.valueOf(revenuData[0])); final BigDecimal amtTargeted = (BigDecimal) revenuData[1]; revnData.put("amtTargeted", amtTargeted != null ? amtTargeted.doubleValue() : "0"); final BigDecimal amt_collectd = (BigDecimal) revenuData[2]; revnData.put("amt_collectd", amt_collectd != null ? amt_collectd.doubleValue() : "0"); final BigDecimal percCollections = (BigDecimal) revenuData[3]; revnData.put("percCollections", percCollections != null ? percCollections.setScale(2, RoundingMode.CEILING).doubleValue() : "0"); } final List<Map<String, Object>> revenueAggrData = new ArrayList<Map<String, Object>>( revenueDataHolder.values()); // SORT BY ZONEWISE MONTHLY COLLECTION % sortData(revenueAggrData, "percCollections"); // ASSIGN MONTHLY RANK BASED ON SORT ORDER assignRank(revenueAggrData, "rank"); // SORT BY ZONEWISE OVERALL COLLECTION % sortData(revenueAggrData, "collectionPerc"); // ASSIGN OVERALL RANK BASED ON SORT ORDER assignRank(revenueAggrData, "overallrank"); return revenueAggrData; }
From source file:org.egov.ptis.repository.dashboard.RevenueDashboardRepository.java
public List<Map<String, Object>> getWardwisePerformanceTab(final String zoneName) { final SQLQuery overAllQry = getQuery("revenue.ptis.wardwise.overall.performance"); overAllQry.setParameter("zoneName", zoneName); final List<Object[]> overAllData = overAllQry.list(); final Map<String, Map<String, Object>> revenueDataHolder = new HashMap<String, Map<String, Object>>(); for (final Object[] revenueObj : overAllData) { final Map<String, Object> revnData = new HashMap<String, Object>(); revnData.put("ward", String.valueOf(revenueObj[0])); final BigDecimal collectionPerc = (BigDecimal) revenueObj[2]; revnData.put("collectionPerc", collectionPerc != null ? collectionPerc.doubleValue() : "0"); revenueDataHolder.put(String.valueOf(revenueObj[0]), revnData); }//from w ww .j a v a 2 s .c om final SQLQuery monthlyQry = getQuery("revenue.ptis.wardwise.monthly.performance"); monthlyQry.setParameter("zoneName", zoneName); final List<Object[]> monthlyData = monthlyQry.list(); for (final Object[] revenueObj : monthlyData) { final Map<String, Object> revnData = revenueDataHolder.get(String.valueOf(revenueObj[0])); final BigDecimal amtTargeted = (BigDecimal) revenueObj[1]; revnData.put("amtTargeted", amtTargeted != null ? amtTargeted.doubleValue() : "0"); final BigDecimal amt_collectd = (BigDecimal) revenueObj[2]; revnData.put("amt_collectd", amt_collectd != null ? amt_collectd.doubleValue() : "0"); final BigDecimal percCollections = (BigDecimal) revenueObj[3]; revnData.put("percCollections", percCollections != null ? percCollections.setScale(2, RoundingMode.CEILING).doubleValue() : "0"); } final List<Map<String, Object>> revenueAggrData = new ArrayList<Map<String, Object>>( revenueDataHolder.values()); // SORT BY WARDWISE MONTHLY COLLECTION % sortData(revenueAggrData, "percCollections"); // ASSIGN MONTHLY RANK BASED ON SORT ORDER assignRank(revenueAggrData, "rank"); // SORT BY WARDWISE OVERALL COLLECTION % sortData(revenueAggrData, "collectionPerc"); // ASSIGN OVERALL RANK BASED ON SORT ORDER assignRank(revenueAggrData, "overallrank"); return revenueAggrData; }
From source file:com.mum.app.AutoSubmitPriceApp.java
public String BuildSubmitPriceXml(Map<String, Float> submitSkuMap) { XmlBuilder xmlBuilder = new XmlBuilder(); xmlBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); xmlBuilder.beginObject("AmazonEnvelope"); xmlBuilder.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlBuilder.writeAttribute("xsi:noNamespaceSchemaLocation", "amznenvelope.xsd"); xmlBuilder.beginObject("Header"); xmlBuilder.write("DocumentVersion", "1.01"); xmlBuilder.write("MerchantIdentifier", AutoSubmitPriceConfig.sellerId); xmlBuilder.endObject("Header"); xmlBuilder.write("MessageType", "Price"); int msgid = 1; for (Entry<String, Float> entry : submitSkuMap.entrySet()) { xmlBuilder.beginObject("Message"); xmlBuilder.write("MessageID", msgid); xmlBuilder.beginObject("Price"); xmlBuilder.write("SKU", entry.getKey()); xmlBuilder.beginObject("StandardPrice"); xmlBuilder.writeAttribute("currency", "USD"); ///*from ww w. j ava2s . c o m*/ BigDecimal b = new BigDecimal(entry.getValue()); Float fvalue = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); xmlBuilder.writeValue(fvalue.toString()); xmlBuilder.endObject("StandardPrice"); xmlBuilder.endObject("Price"); xmlBuilder.endObject("Message"); msgid++; } xmlBuilder.endObject("AmazonEnvelope"); return xmlBuilder.toString(); }
From source file:org.kuali.kfs.module.bc.businessobject.CalculatedSalaryFoundationTracker.java
/** * Gets the csfTimePercent attribute. Returns 2 decimal places, reguardless. * * @return Returns the csfTimePercent/*from w w w . j a v a2 s . com*/ */ public BigDecimal getCsfTimePercent() { BigDecimal bigDecValue = this.csfTimePercent; bigDecValue = bigDecValue.setScale(PERCENTAGE_SCALE, BigDecimal.ROUND_HALF_UP); return bigDecValue; }
From source file:com.abiquo.api.services.cloud.VirtualApplianceService.java
private BigDecimal rounded(final int significantDigits, final BigDecimal aNumber) { return aNumber.setScale(significantDigits, BigDecimal.ROUND_UP); }
From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java
@Override public int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent, final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz, final boolean includeAdditionalTime) { boolean isTjDivisable = operationComponent.getBooleanField("isTjDivisible"); Integer workstationsCount = retrieveWorkstationTypesCount(operationComponent, productionLine); BigDecimal cyclesPerOperation = cycles; if (maxForWorkstation) { cyclesPerOperation = cycles.divide(BigDecimal.valueOf(workstationsCount), numberService.getMathContext()); if (!isTjDivisable) { cyclesPerOperation = cyclesPerOperation.setScale(0, RoundingMode.CEILING); }/*from w w w.j a va2 s . c om*/ } int tj = getIntegerValue(operationComponent.getField("tj")); int operationTime = cyclesPerOperation.multiply(BigDecimal.valueOf(tj), numberService.getMathContext()) .intValue(); if (includeTpz) { int tpz = getIntegerValue(operationComponent.getField("tpz")); operationTime += (maxForWorkstation ? tpz : (tpz * workstationsCount)); } if (includeAdditionalTime) { int additionalTime = getIntegerValue(operationComponent.getField("timeNextOperation")); operationTime += (maxForWorkstation ? additionalTime : (additionalTime * workstationsCount)); } return operationTime; }
From source file:org.diretto.web.richwebclient.view.sections.UploadSection.java
/** * Uploads the currently processed file. * /*from w ww . j ava 2 s . c om*/ * @param uploadSettings The {@code UploadSettings} of the file * @param filesWithSameSettings A {@code List} with the names of the files * which should get the given {@code UploadSettings} as presetting */ public void upload(final UploadSettings uploadSettings, List<String> filesWithSameSettings) { final FileInfo fileInfo = currentFile; settings.put(fileInfo.getName(), uploadSettings); for (String fileName : filesWithSameSettings) { preSettings.put(fileName, uploadSettings); } new Thread(new Runnable() { @Override public void run() { ProgressIndicator progressIndicator = multipleUpload.upload(fileInfo); synchronized (application) { VerticalLayout uploadBoxLayout = new VerticalLayout(); mainLayout.addComponent(uploadBoxLayout); HorizontalLayout fileInfoLayout = new HorizontalLayout(); uploadBoxLayout.addComponent(fileInfoLayout); Label nameLabel = StyleUtils.getLabelBold(fileInfo.getName()); fileInfoLayout.addComponent(nameLabel); fileInfoLayout.addComponent(StyleUtils.getLabelSmallHTML(" ")); fileInfoLayout.setComponentAlignment(nameLabel, Alignment.MIDDLE_LEFT); BigDecimal fileSize = new BigDecimal((((double) fileInfo.getSize()) / 1000000.0d)); fileSize = fileSize.setScale(2, BigDecimal.ROUND_HALF_UP); Label typeSizeLabel = StyleUtils.getLabelSmallHTML( fileInfo.getType() + " -- " + fileSize.toPlainString() + " MB"); fileInfoLayout.addComponent(typeSizeLabel); fileInfoLayout.setComponentAlignment(typeSizeLabel, Alignment.MIDDLE_LEFT); uploadBoxLayout.addComponent(StyleUtils.getVerticalSpace("100%", "8px")); uploadBoxLayout.addComponent(progressIndicator); uploadBoxLayout.addComponent(StyleUtils.getVerticalSpace("100%", "8px")); HorizontalLayout resultLayout = new HorizontalLayout(); uploadBoxLayout.addComponent(resultLayout); Label uploadedLabel = StyleUtils.getLabelSmallHTML("Uploaded: "); resultLayout.addComponent(uploadedLabel); resultLayout.setComponentAlignment(uploadedLabel, Alignment.MIDDLE_LEFT); Embedded uploadedEmbedded = new Embedded(null, ResourceUtils.RUNO_ICON_32_GLOBE_RESOURCE); uploadedEmbedded.addStyleName("image-opacity-65"); uploadedEmbedded.setType(Embedded.TYPE_IMAGE); uploadedEmbedded.setImmediate(true); uploadedEmbedded.setWidth("22px"); uploadedEmbedded.setHeight("22px"); resultLayout.addComponent(uploadedEmbedded); uploadedEmbeddeds.put(fileInfo, uploadedEmbedded); resultLayout.addComponent(StyleUtils.getLabelSmallHTML(" ")); Label publishedLabel = StyleUtils.getLabelSmallHTML("Published: "); resultLayout.addComponent(publishedLabel); resultLayout.setComponentAlignment(publishedLabel, Alignment.MIDDLE_LEFT); Embedded publishedEmbedded = new Embedded(null, ResourceUtils.RUNO_ICON_32_GLOBE_RESOURCE); publishedEmbedded.addStyleName("image-opacity-65"); publishedEmbedded.setType(Embedded.TYPE_IMAGE); publishedEmbedded.setImmediate(true); publishedEmbedded.setWidth("22px"); publishedEmbedded.setHeight("22px"); resultLayout.addComponent(publishedEmbedded); publishedEmbeddeds.put(fileInfo, publishedEmbedded); mainLayout.addComponent(StyleUtils.getVerticalSpace("100%", "5px")); requestRepaint(); } } }).start(); handleNextFile(); }