List of usage examples for java.math RoundingMode HALF_UP
RoundingMode HALF_UP
To view the source code for java.math RoundingMode HALF_UP.
Click Source Link
From source file:org.projectforge.business.fibu.datev.EmployeeSalaryExportDao.java
private void addEmployeeRow(final ExportSheet sheet, final EmployeeDO employee, final BigDecimal numberOfWorkingDays, final BigDecimal totalDuration) { final PFUserDO user = getUserGroupCache().getUser(employee.getUserId()); final ExportRow row = sheet.addRow(); row.addCell(0, user.getFullname());/*w ww . ja v a 2s . c o m*/ // Wochenstunden row.addCell(1, employee.getWeeklyWorkingHours(), "STUNDEN"); // Sollstunden: Wochenstunden * Arbeitstage / 5 Arbeitstage pro Woche BigDecimal wochenstunden = employee.getWeeklyWorkingHours(); if (wochenstunden == null) { wochenstunden = BigDecimal.ZERO; } final BigDecimal soll = wochenstunden.multiply(numberOfWorkingDays).divide(new BigDecimal(5), 2, RoundingMode.HALF_UP); row.addCell(2, soll, "STUNDEN"); // Iststunden final BigDecimal total = totalDuration.divide(new BigDecimal(3600000), 2, RoundingMode.HALF_UP); row.addCell(3, total, "STUNDEN"); // Differenz final BigDecimal differenz = total.subtract(soll); row.addCell(4, differenz, "STUNDEN"); }
From source file:org.sakaiproject.profile2.job.KudosJob.java
public void execute(JobExecutionContext context) throws JobExecutionException { //abort if already running on THIS server node (cannot check other nodes) try {/*from w w w .j a v a2 s . co m*/ while (isJobCurrentlyRunning(context)) { String beanId = context.getJobDetail().getJobDataMap().getString(BEAN_ID); log.warn("Another instance of " + beanId + " is currently running - Execution aborted."); return; } } catch (SchedulerException e) { log.error("Aborting job execution due to " + e.toString(), e); return; } log.info("KudosJob run"); //start a session for admin so we can get full profiles Session session = sessionManager.startSession(); sessionManager.setCurrentSession(session); session.setUserEid("admin"); session.setUserId("admin"); //get total possible score BigDecimal total = getTotal(); log.info("Total score possible: " + total.setScale(2, RoundingMode.HALF_UP)); //get total number of records List<String> profileUuids = profileLogic.getAllSakaiPersonIds(); //iterate over list getting a chunk of profiles at a time for (String userUuid : profileUuids) { Person person = profileLogic.getPerson(userUuid); if (person == null) { continue; } log.info("Processing user: " + userUuid + " (" + person.getDisplayName() + ")"); //get score for user BigDecimal score = getScore(person); BigDecimal percentage = getScoreAsPercentage(score, total); int adjustedScore = getScoreOutOfTen(score, total); //save it if (kudosLogic.updateKudos(userUuid, adjustedScore, percentage)) { log.info("Kudos updated for user: " + userUuid + ", score: " + score.setScale(2, RoundingMode.HALF_UP) + ", percentage: " + percentage + ", adjustedScore: " + adjustedScore); } } session.setUserId(null); session.setUserEid(null); log.info("KudosJob finished"); }
From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java
/** * Adds positive or negative influence to the start value, depending on the * quality of the master data objects.//ww w .j a v a2 s . c o m * * @param influencingMasterDataQuality list of influencing master data quality * @param higherIsBetter true if positiv influence shall be added, negative * influence otherwise * @param influence influence value to be added to the start value * @param startValue the start value * @return aggregated start value */ protected Float getValue(List<Float> influencingMasterDataQuality, boolean higherIsBetter, Float influence, Float startValue) { Float value = startValue; BigDecimal influenceCount = BigDecimal.ZERO; for (float quality : influencingMasterDataQuality) { // check quality value of the masterdata and adjust the result value influenceCount = influenceCount.add(BigDecimal.valueOf(quality)); } if (influenceCount.compareTo(BigDecimal.ZERO) > 0) { influenceCount = influenceCount.setScale(2, BigDecimal.ROUND_HALF_UP); // normalize the quality value influenceCount = influenceCount.divide(BigDecimal.valueOf(influencingMasterDataQuality.size()), 8, RoundingMode.HALF_UP); // subtract the avg normal, for standard config it is 0.5 influenceCount = influenceCount.subtract(getAvgNormal()); // if the normalized value is greater than the avg if (influenceCount.compareTo(BigDecimal.ZERO) == 1) { // calculate how much times the value is greater than the difference // between the avg normal value and the lowest good value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityGood()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); // if the normalized value is LOWER than the avg } else if (influenceCount.compareTo(BigDecimal.ZERO) == -1) { // calculate how much times the value is smaller than the difference // between the avg normal value and the lowest normal value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityNormal()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); } } influence *= influenceCount.intValue(); if (higherIsBetter) { value += influence; } else { value -= influence; } return value; }
From source file:org.kuali.ole.module.purap.document.web.struts.OlePurchaseOrderAction.java
/** * @see org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from ww w . java 2 s. co m @Override public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems(); for (PurApItem purApItem : purApItems) { List<KualiDecimal> existingAmount = new ArrayList<>(); for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) { if (((OlePurchaseOrderAccount) oldSourceAccountingLine).getExistingAmount() != null) { existingAmount.add(((OlePurchaseOrderAccount) oldSourceAccountingLine).getExistingAmount()); } } } int count = 0; for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (account.getAmount() != null && count < existingAmount.size() && existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) { KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount() .multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString()); account.setAccountLinePercent(calculatedPercent.bigDecimalValue() .setScale(OLEConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING)); } else { if (account.getAccountLinePercent().intValue() == 100 && (account.getAmount() == null || account.getAccount() != null)) { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } else { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } } count++; } for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) { ((OlePurchaseOrderAccount) oldSourceAccountingLine) .setExistingAmount(oldSourceAccountingLine.getAmount()); } } } ActionForward forward = super.calculate(mapping, form, request, response); /* calculateCurrency(mapping, form, request, response); */ purchasingForm = (PurchasingAccountsPayableFormBase) form; PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument(); PurchasingFormBase formBase = (PurchasingFormBase) form; PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) formBase.getDocument(); List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems(); if (purchaseDoc.getVendorDetail().getCurrencyType() != null) { if (purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && currencyTypeIndicator)) { for (int i = 0; purDoc.getItems().size() > i; i++) { OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i); if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new DiscountPurchaseOrderEvent(purchaseDoc, item)); if (rulePassed) { item.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item) .setScale(2, BigDecimal.ROUND_HALF_UP)); } rulePassed = getKualiRuleService().applyRules(new CopiesPurchaseOrderEvent(purDoc, item)); } } } else { LOG.debug("###########Foreign Currency Field Calculation in olepurchaseOrder action###########"); BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class); for (int i = 0; purItem.size() > i; i++) { OlePurchaseOrderItem items = (OlePurchaseOrderItem) purchaseDoc.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new ForeignCurrencyPOEvent(purchaseDoc, items)); if (rulePassed) { SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items); Long id = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map currencyTypeMap = new HashMap(); currencyTypeMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id); List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy( OleExchangeRate.class, currencyTypeMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); String documentNumber = purchaseDoc.getDocumentNumber(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OLEPropertyConstants.DOCUMENT_NUMBER, documentNumber); List<OlePurchaseOrderItem> currenctExchangeRateList = (List) businessObjectService .findMatching(OlePurchaseOrderItem.class, documentNumberMap); Iterator iterate = currenctExchangeRateList.iterator(); if (iterate.hasNext()) { OlePurchaseOrderItem tempCurrentExchangeRate = (OlePurchaseOrderItem) iterate .next(); String poCurrencyType = null; if (tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail() .getCurrencyType() != null) { poCurrencyType = tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail() .getCurrencyType().getCurrencyType(); } String poaCurrencyType = purchaseDoc.getVendorDetail().getCurrencyType() .getCurrencyType(); if (poCurrencyType != null && (poCurrencyType.equalsIgnoreCase(poaCurrencyType)) && !items.isLatestExchangeRate() && !purchaseDoc.getIsPODoc() && ((purchaseDoc instanceof PurchaseOrderAmendmentDocument) || (purchaseDoc instanceof PurchaseOrderSplitDocument) || (purchaseDoc instanceof PurchaseOrderReopenDocument))) { items.setItemExchangeRate(tempCurrentExchangeRate.getItemExchangeRate()); } else { items.setItemExchangeRate( new KualiDecimal(tempOleExchangeRate.getExchangeRate())); } } if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) { items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost() .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP))); items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP)); items.setItemListPrice(items.getItemUnitCostUSD()); } } } } } } purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()) .getItems(); for (PurApItem purApItem : newpurApItems) { for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { KualiDecimal calculatedAmount = new KualiDecimal( account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } forward = super.calculate(mapping, form, request, response); // setEnumerationToCopies(purItem); // Added for SFC - Start OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext .getBean("oleRequisitionDocumentService"); List<SourceAccountingLine> sourceAccountingLineList = purDoc.getSourceAccountingLines(); for (SourceAccountingLine accLine : sourceAccountingLineList) { String notificationOption = null; boolean sufficientFundCheck; Map<String, Object> key = new HashMap<String, Object>(); String chartCode = accLine.getChartOfAccountsCode(); String accNo = accLine.getAccountNumber(); key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode); key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo); OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class) .findByPrimaryKey(OleSufficientFundCheck.class, key); if (account != null) { notificationOption = account.getNotificationOption(); } if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) { sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine); if (sufficientFundCheck) { GlobalVariables.getMessageMap().putError( OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM, OLEConstants.SufficientFundCheck.INSUFF_FUND_POA + accLine.getAccountNumber()); } } } // End // formBase.setCalculated(true); if (LOG.isDebugEnabled()) { LOG.debug("Inside the OlePurchaseOrderAction class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice()); } return forward; }
From source file:org.cgiar.ccafs.marlo.action.projects.ProjectBudgetByClusterOfActivitiesAction.java
public double round(double value, int places) { if (places < 0) { throw new IllegalArgumentException(); }/* w w w. j a va 2 s . c o m*/ BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
From source file:de.jfachwert.math.PackedDecimal.java
/** * Dividiert den uebergebenen Operanden und liefert als Ergebnis eine neue * {@link PackedDecimal} zurueck/* w ww.j a v a 2 s .c o m*/ * * @param operand Operand * @return Ergebnis der Division */ public PackedDecimal divide(BigDecimal operand) { BigDecimal result = toBigDecimal().divide(operand, RoundingMode.HALF_UP); return PackedDecimal.valueOf(result); }
From source file:com.streamsets.pipeline.lib.salesforce.SobjectRecordCreator.java
com.streamsets.pipeline.api.Field createField(Object val, DataType userSpecifiedType, Field sfdcField) throws StageException { String sfdcType = sfdcField.getType().toString(); if (userSpecifiedType != DataType.USE_SALESFORCE_TYPE) { return com.streamsets.pipeline.api.Field .create(com.streamsets.pipeline.api.Field.Type.valueOf(userSpecifiedType.getLabel()), val); } else {//from w w w. j a va 2 s . c o m if (val instanceof Map || ANYTYPE.equals(sfdcType)) { // Fields like Fiscal on Opportunity show up as Maps from Streaming API // anyType can be String, boolean etc try { return JsonUtil.jsonToField(val); } catch (IOException e) { throw new StageException(Errors.FORCE_04, "Error parsing data", e); } } else if (BOOLEAN_TYPES.contains(sfdcType)) { return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.BOOLEAN, val); } else if (BYTE_TYPES.contains(sfdcType)) { return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.BYTE, val); } else if (INT_TYPES.contains(sfdcType)) { return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.INTEGER, val); } else if (DECIMAL_TYPES.contains(sfdcType)) { // Salesforce can return a string value with greater scale than that defined in the schema - see SDC-10152 // Ensure that the created BigDecimal value matches the Salesforce schema return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.DECIMAL, (val == null) ? null : (new BigDecimal(val.toString())).setScale(sfdcField.getScale(), RoundingMode.HALF_UP)); } else if (STRING_TYPES.contains(sfdcType)) { return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.STRING, val); } else if (BINARY_TYPES.contains(sfdcType)) { return com.streamsets.pipeline.api.Field.create(com.streamsets.pipeline.api.Field.Type.BYTE_ARRAY, val); } else if (DATETIME_TYPES.contains(sfdcType)) { if (val != null && !(val instanceof String)) { throw new StageException(Errors.FORCE_04, UNEXPECTED_TYPE + val.getClass().getName()); } String strVal = (String) val; try { return com.streamsets.pipeline.api.Field .createDatetime((strVal != null) ? datetimeFormat.parse(strVal) : null); } catch (ParseException e) { throw new StageException(Errors.FORCE_04, "Error parsing date", e); } } else if (DATE_TYPES.contains(sfdcType)) { if (val != null && !(val instanceof String)) { throw new StageException(Errors.FORCE_04, UNEXPECTED_TYPE + val.getClass().getName()); } String strVal = (String) val; try { return com.streamsets.pipeline.api.Field .createDatetime((strVal != null) ? dateFormat.parse(strVal) : null); } catch (ParseException e) { throw new StageException(Errors.FORCE_04, "Error parsing date", e); } } else { throw new StageException(Errors.FORCE_04, UNEXPECTED_TYPE + sfdcType); } } }
From source file:org.yes.cart.payment.impl.CyberSourcePaymentGatewayImpl.java
/** * {@inheritDoc}//from w ww . ja v a2 s . c o m */ public Payment reverseAuthorization(final Payment payment) { final Logger log = ShopCodeContext.getLog(this); if (log.isDebugEnabled()) { log.debug("Reverse authorization " + payment); } final HashMap<String, String> request = new HashMap<String, String>(); request.put("ccAuthReversalService_run", "true"); request.put("ccAuthReversalService_authRequestID", payment.getTransactionAuthorizationCode()); request.put("ccAuthReversalService_authRequestToken", payment.getTransactionRequestToken()); request.put("purchaseTotals_currency", payment.getOrderCurrency()); request.put("purchaseTotals_grandTotalAmount", payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString()); request.put("merchantID", (String) getProperties().get(CS_MERCHANT_ID)); request.put("requestID", payment.getTransactionAuthorizationCode()); request.put("requestToken", payment.getTransactionRequestToken()); request.put("merchantReferenceCode", payment.getTransactionReferenceId()); return runTransaction(request, payment, REVERSE_AUTH); }
From source file:com.almunt.jgcaap.systemupdater.MainActivity.java
public static 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:org.egov.tl.service.TradeLicenseService.java
public void calcPenaltyDemandDetails(TradeLicense license, EgDemand demand) { Map<Installment, BigDecimal> installmentPenalty = new HashMap<>(); Map<Installment, EgDemandDetails> penaltyDetails = getInstallmentWisePenaltyDemandDetails(demand); Map<Installment, EgDemandDetails> demandDetails = getInstallmentWiseLicenseDemandDetails(demand); if (license.isNewApplication()) installmentPenalty = getCalculatedPenalty(license, license.getCommencementDate(), new Date(), demand); else if (license.isReNewApplication()) installmentPenalty = getCalculatedPenalty(license, null, new Date(), demand); for (final Map.Entry<Installment, BigDecimal> penalty : installmentPenalty.entrySet()) { EgDemandDetails penaltyDemandDetail = penaltyDetails.get(penalty.getKey()); EgDemandDetails licenseDemandDetail = demandDetails.get(penalty.getKey()); if (penalty.getValue().signum() > 0) { if (penaltyDemandDetail != null && licenseDemandDetail.getBalance().signum() > 0) penaltyDemandDetail.setAmount(penalty.getValue().setScale(0, RoundingMode.HALF_UP)); else if (licenseDemandDetail.getBalance().signum() > 0) { penaltyDemandDetail = insertPenaltyDmdDetail(penalty.getKey(), penalty.getValue().setScale(0, RoundingMode.HALF_UP)); if (penaltyDemandDetail != null) demand.getEgDemandDetails().add(penaltyDemandDetail); }/*from w w w .ja v a2s.c om*/ } else if (penalty.getValue().signum() == 0 && penaltyDemandDetail != null) { penaltyDemandDetail.setAmount(penalty.getValue().setScale(0, RoundingMode.HALF_UP)); } } }