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.kuali.ole.select.document.validation.impl.OleInvoiceValidation.java
public boolean validate(AttributedDocumentEvent event) { boolean valid = true; OleInvoiceDocument document = (OleInvoiceDocument) event.getDocument(); GlobalVariables.getMessageMap().clearErrorPath(); GlobalVariables.getMessageMap().addToErrorPath(OLEPropertyConstants.DOCUMENT); PurchaseOrderDocument po = null;//ww w . j a v a2s .c o m if (ObjectUtils.isNull(document.getPurchaseOrderIdentifier())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_REQUIRED, PRQSDocumentsStrings.PURCHASE_ORDER_ID); valid &= false; } else { po = SpringContext.getBean(PurchaseOrderService.class) .getCurrentPurchaseOrder(document.getPurchaseOrderIdentifier()); } if (ObjectUtils.isNull(document.getInvoiceDate())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.INVOICE_DATE, OLEKeyConstants.ERROR_REQUIRED, PRQSDocumentsStrings.INVOICE_DATE); valid &= false; } /* if (StringUtils.isBlank(document.getInvoiceNumber())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.INVOICE_NUMBER, OLEKeyConstants.ERROR_REQUIRED, PRQSDocumentsStrings.INVOICE_NUMBER); valid &= false; }*/ if (document.getInvoiceCurrencyType() != null) { String currencyType = SpringContext.getBean(OleInvoiceService.class) .getCurrencyType(document.getInvoiceCurrencyType()); if (StringUtils.isNotBlank(currencyType)) { if (currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } } if (!currencyTypeIndicator) { if (ObjectUtils.isNull(document.getForeignVendorInvoiceAmount())) { GlobalVariables.getMessageMap().putError(OleSelectConstant.FOREIGN_VENDOR_INVOICE_AMOUNT, OLEKeyConstants.ERROR_REQUIRED, OleSelectConstant.FOREIGN_VENDOR_INVOICE_AMOUNT_STRING); valid &= false; } else { Long currencyTypeId = po.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId); org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext .getBean(org.kuali.rice.krad.service.BusinessObjectService.class); List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); document.setVendorInvoiceAmount(new KualiDecimal(document.getForeignVendorInvoiceAmount() .divide(tempOleExchangeRate.getExchangeRate(), 4, RoundingMode.HALF_UP))); } } } if (ObjectUtils.isNull(document.getVendorInvoiceAmount())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.VENDOR_INVOICE_AMOUNT, OLEKeyConstants.ERROR_REQUIRED, PRQSDocumentsStrings.VENDOR_INVOICE_AMOUNT); valid &= false; } GlobalVariables.getMessageMap().clearErrorPath(); return valid; }
From source file:org.openhab.binding.pilight.internal.PilightBinding.java
protected State getState(String value, PilightBindingConfig config) { State state = null;//www . j a v a 2s. com if (config.getItemType().equals(StringItem.class)) { state = new StringType(value); } else if (config.getItemType().equals(NumberItem.class)) { if (!StringUtils.isBlank(value)) { // Number values are always received as an integer with an optional parameter describing // the number of decimals (scale, default = 0). BigDecimal numberValue = new BigDecimal(value); numberValue = numberValue.divide(new BigDecimal(Math.pow(10, config.getScale())), config.getScale(), RoundingMode.HALF_UP); state = new DecimalType(numberValue); } } return state; }
From source file:me.smoe.adar.utils.cam.o.CAMApplication.java
private void go(int cases, boolean buildScore) throws Exception { if (buildScore) { statistics.run();/*from w w w .j ava 2s. c om*/ } Map<Long, String> cams = new HashMap<>(); for (CAM cam : camRepository.findAll()) { cams.put(cam.getId(), cam.getName()); } AtomicInteger succ = new AtomicInteger(); AtomicInteger fail = new AtomicInteger(); AtomicInteger wrong = new AtomicInteger(); AtomicInteger index = new AtomicInteger(); Page<CAMProduct> products = camProductRepository .findAll(new PageRequest(0, cases, new Sort(Direction.DESC, "id"))); int total = products.getSize(); for (CAMProduct product : products) { THREADPOOLEXECUTOR.execute(() -> { try { Long ca = caMatcher.matcher(product.getName(), product.getBrand(), product.getCategory(), product.getDesc(), 10000); // Long ca = me.smoe.adar.utils.cam.n.matcher.CAMatcher.matcher(product.getCategory(), 20); if (product.getCao().equals(ca)) { System.err.println( String.format("[CAM] Index: %s Id: %s Cao: %s Can: %s", index.incrementAndGet(), product.getId(), cams.get(product.getCao()), cams.get(ca))); } else if (ca != null && cams.get(product.getCao()).equals(cams.get(ca))) { System.err.println( String.format("[CAM] Index: %s Id: %s Cao: %s Can: %s", index.incrementAndGet(), product.getId(), cams.get(product.getCao()), cams.get(ca))); } else if (ca != null) { System.out.println( String.format("[CAM] Index: %s Id: %s Cao: %s Can: %s", index.incrementAndGet(), product.getId(), cams.get(product.getCao()), cams.get(ca))); } else { // System.out.println(String.format("[CAM] Index: %s Id: %s Cao: %s Can: %s", index.incrementAndGet(), product.getId(), cams.get(product.getCao()), cams.get(ca))); } if (ca == null) { fail.incrementAndGet(); return; } if (product.getCao().equals(ca)) { succ.incrementAndGet(); } else if (ca != null && cams.get(product.getCao()).equals(cams.get(ca))) { succ.incrementAndGet(); } else { wrong.incrementAndGet(); } } catch (Exception e) { e.printStackTrace(); } }); } while (!THREADPOOLEXECUTOR.getQueue().isEmpty()) { TimeUnit.SECONDS.sleep(1); } TimeUnit.SECONDS.sleep(2); System.out.println(); System.out.println("[CAM] : " + total); System.out.println("[CAM] ?: " + new BigDecimal(succ.get()).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP) .multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%"); System.out.println("[CAM] : " + new BigDecimal(fail.get()).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP) .multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%"); System.out.println("[CAM] : " + new BigDecimal(wrong.get()).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP) .multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%"); System.exit(0); }
From source file:org.openbravo.costing.CostingServer.java
/** * Calculates and stores in the database the cost of the transaction. * //from w ww . j ava2 s . c o m * */ public void process() { try { if (trxCost != null) { // Transaction cost has already been calculated. Nothing to do. return; } log4j.debug("Process cost"); try { OBContext.setAdminMode(false); // Get needed algorithm. And set it in the M_Transaction. CostingAlgorithm costingAlgorithm = getCostingAlgorithm(); costingAlgorithm.init(this); log4j.debug(" *** Algorithm initializated: " + costingAlgorithm.getClass()); trxCost = costingAlgorithm.getTransactionCost(); if (trxCost == null && !transaction.getCostingStatus().equals("P")) { throw new OBException("@NoCostCalculated@: " + transaction.getIdentifier()); } if (transaction.getCostingStatus().equals("P")) { return; } trxCost = trxCost.setScale(costingAlgorithm.getCostCurrency().getStandardPrecision().intValue(), RoundingMode.HALF_UP); log4j.debug(" *** Transaction cost amount: " + trxCost.toString()); // Save calculated cost on M_Transaction. transaction = OBDal.getInstance().get(MaterialTransaction.class, transaction.getId()); transaction.setTransactionCost(trxCost); transaction.setCurrency(currency); transaction.setCostCalculated(true); transaction.setCostingStatus("CC"); // insert on m_transaction_cost createTransactionCost(); OBDal.getInstance().flush(); setNotPostedTransaction(); checkCostAdjustments(); } finally { OBContext.restorePreviousMode(); } return; } finally { // Every Transaction must be set as Processed = 'Y' after going through this method transaction.setProcessed(true); OBDal.getInstance().flush(); } }
From source file:org.openhab.binding.jeelink.internal.lacrosse.LaCrosseTemperatureSensorHandler.java
public ReadingPublisher<LaCrosseTemperatureReading> createPublisherForChannel(int channelNo) { ReadingPublisher<LaCrosseTemperatureReading> publisher = new ReadingPublisher<LaCrosseTemperatureReading>() { @Override//from ww w . j a va2 s. c o m public void publish(LaCrosseTemperatureReading reading) { if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) { BigDecimal temp = new BigDecimal(reading.getTemperature()).setScale(1, RoundingMode.HALF_UP); if (channelNo == 1) { logger.debug( "updating states for thing {} ({}): temp={} ({}), humidity={}, batteryNew={}, batteryLow={}", getThing().getLabel(), getThing().getUID().getId(), temp, reading.getTemperature(), reading.getHumidity(), reading.isBatteryNew(), reading.isBatteryLow()); updateState(TEMPERATURE_CHANNEL, new QuantityType<>(temp, SIUnits.CELSIUS)); updateState(HUMIDITY_CHANNEL, new QuantityType<>(reading.getHumidity(), SmartHomeUnits.PERCENT)); updateState(BATTERY_NEW_CHANNEL, reading.isBatteryNew() ? OnOffType.ON : OnOffType.OFF); updateState(BATTERY_LOW_CHANNEL, reading.isBatteryLow() ? OnOffType.ON : OnOffType.OFF); } else { logger.debug("updating states for channel {} of thing {} ({}): temp={} ({}), humidity={}", reading.getChannel(), getThing().getLabel(), getThing().getUID().getId(), temp, reading.getTemperature(), reading.getHumidity()); updateState(TEMPERATURE_CHANNEL + reading.getChannel(), new QuantityType<>(temp, SIUnits.CELSIUS)); updateState(HUMIDITY_CHANNEL + reading.getChannel(), new QuantityType<>(reading.getHumidity(), SmartHomeUnits.PERCENT)); } } } @Override public void dispose() { } }; LaCrosseTemperatureSensorConfig cfg = getConfigAs(LaCrosseTemperatureSensorConfig.class); if (cfg.bufferSize > 1 && cfg.updateInterval > 0) { publisher = new RollingAveragePublisher<LaCrosseTemperatureReading>(cfg.bufferSize, cfg.updateInterval, publisher, scheduler) { @Override public RollingReadingAverage<LaCrosseTemperatureReading> createRollingReadingAverage( int bufferSize) { return new LaCrosseRollingReadingAverage(bufferSize); } }; } if (cfg.maxDiff > 0) { publisher = new DifferenceCheckingPublisher(cfg.maxDiff, publisher); } publisher = new BoundsCheckingPublisher(cfg.minTemp, cfg.maxTemp, publisher); return publisher; }
From source file:org.yes.cart.web.page.component.price.PriceView.java
/** * Get whole and decimal part of money to render. * @param price price//from ww w.j a v a 2 s . c o m * @return array of string to render. */ String[] getFormattedPrice(BigDecimal price) { final String[] formatted; if (MoneyUtils.isFirstBiggerThanOrEqualToSecond(price, BigDecimal.ZERO)) { // show zeros! final String priceString = price.setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP) .toPlainString(); formatted = StringUtils.split(priceString, '.'); } else { // if price was null formatted = EMPTY_FORMATED_PRICE; } return formatted; }
From source file:org.openbravo.costing.PriceDifferenceProcess.java
private static boolean calculateTransactionPriceDifferenceLogic(MaterialTransaction materialTransaction) throws OBException { boolean costAdjCreated = false; // With Standard Algorithm, no cost adjustment is needed if (StringUtils.equals(materialTransaction.getCostingAlgorithm().getJavaClassName(), "org.openbravo.costing.StandardAlgorithm")) { return false; }/* ww w. j av a2s. c om*/ if (materialTransaction.isCostPermanent()) { // Permanently adjusted transaction costs are not checked for price differences. return false; } Currency trxCurrency = materialTransaction.getCurrency(); Organization trxOrg = materialTransaction.getOrganization(); Date trxDate = materialTransaction.getMovementDate(); int costCurPrecission = trxCurrency.getCostingPrecision().intValue(); ShipmentInOutLine receiptLine = materialTransaction.getGoodsShipmentLine(); if (receiptLine == null || !isValidPriceAdjTrx(receiptLine.getMaterialMgmtMaterialTransactionList().get(0))) { // We can only adjust cost of receipt lines. return false; } BigDecimal receiptQty = receiptLine.getMovementQuantity(); boolean isNegativeReceipt = receiptQty.signum() == -1; if (isNegativeReceipt) { // If the receipt is negative convert the quantity to positive. receiptQty = receiptQty.negate(); } Date costAdjDateAcct = null; BigDecimal invoiceAmt = BigDecimal.ZERO; // Calculate current transaction unit cost including existing adjustments. BigDecimal currentTrxUnitCost = CostAdjustmentUtils.getTrxCost(materialTransaction, true, trxCurrency); // Calculate expected transaction unit cost based on current invoice amounts and purchase price. BigDecimal expectedCost = BigDecimal.ZERO; BigDecimal invoiceQty = BigDecimal.ZERO; for (ReceiptInvoiceMatch matchInv : receiptLine.getProcurementReceiptInvoiceMatchList()) { Invoice invoice = matchInv.getInvoiceLine().getInvoice(); if (invoice.getDocumentStatus().equals("VO")) { // Skip voided invoices. continue; } if (!invoice.isProcessed()) { // Skip not processed invoices. continue; } if (isNegativeReceipt) { // If the receipt is negative negate the invoiced quantities. invoiceQty = invoiceQty.add(matchInv.getQuantity().negate()); } else { invoiceQty = invoiceQty.add(matchInv.getQuantity()); } invoiceAmt = matchInv.getQuantity().multiply(matchInv.getInvoiceLine().getUnitPrice()); invoiceAmt = FinancialUtils.getConvertedAmount(invoiceAmt, invoice.getCurrency(), trxCurrency, trxDate, trxOrg, FinancialUtils.PRECISION_STANDARD, invoice.getCurrencyConversionRateDocList()); expectedCost = expectedCost.add(invoiceAmt); Date invoiceDate = invoice.getInvoiceDate(); if (costAdjDateAcct == null || costAdjDateAcct.before(invoiceDate)) { costAdjDateAcct = invoiceDate; } } BigDecimal notInvoicedQty = receiptQty.subtract(invoiceQty); if (notInvoicedQty.signum() > 0) { // Not all the receipt line is invoiced, add pending invoice quantity valued with current // order price if exists or original unit cost. BigDecimal basePrice = BigDecimal.ZERO; Currency baseCurrency = trxCurrency; if (receiptLine.getSalesOrderLine() != null) { basePrice = receiptLine.getSalesOrderLine().getUnitPrice(); baseCurrency = receiptLine.getSalesOrderLine().getSalesOrder().getCurrency(); } else { basePrice = materialTransaction.getTransactionCost().divide(receiptQty, costCurPrecission, RoundingMode.HALF_UP); } BigDecimal baseAmt = notInvoicedQty.multiply(basePrice).setScale(costCurPrecission, RoundingMode.HALF_UP); if (!baseCurrency.getId().equals(trxCurrency.getId())) { baseAmt = FinancialUtils.getConvertedAmount(baseAmt, baseCurrency, trxCurrency, trxDate, trxOrg, FinancialUtils.PRECISION_STANDARD); } expectedCost = expectedCost.add(baseAmt); } // if the sum of trx costs with flag "isInvoiceCorrection" is distinct that the amount cost // generated by Match Invoice then New Cost Adjustment line is created by the difference if (expectedCost.compareTo(currentTrxUnitCost) != 0) { if (costAdjDateAcct == null) { costAdjDateAcct = trxDate; } createCostAdjustmenHeader(trxOrg); CostAdjustmentLine costAdjLine = CostAdjustmentUtils.insertCostAdjustmentLine(materialTransaction, costAdjHeader, expectedCost.subtract(currentTrxUnitCost), Boolean.TRUE, costAdjDateAcct); costAdjLine.setNeedsPosting(Boolean.TRUE); OBDal.getInstance().save(costAdjLine); costAdjCreated = true; } return costAdjCreated; }
From source file:org.openhab.binding.astro.internal.bus.PlanetPublisher.java
/** * Publishes the item with the value, if the item is a OnOffType and the * value is a calendar, a job is scheduled. *//*from w w w. j a va2 s .c o m*/ private void publishValue(Item item, Object value, AstroBindingConfig bindingConfig) { if (value == null) { context.getEventPublisher().postUpdate(item.getName(), UnDefType.UNDEF); } else if (value instanceof Calendar) { Calendar calendar = (Calendar) value; if (bindingConfig.getOffset() != 0) { calendar = (Calendar) calendar.clone(); calendar.add(Calendar.MINUTE, bindingConfig.getOffset()); } if (item.getAcceptedDataTypes().contains(DateTimeType.class)) { context.getEventPublisher().postUpdate(item.getName(), new DateTimeType(calendar)); } else if (item.getAcceptedCommandTypes().contains(OnOffType.class)) { context.getJobScheduler().scheduleItem(calendar, item.getName()); } else { logger.warn("Unsupported type for item {}, only DateTimeType and OnOffType supported!", item.getName()); } } else if (value instanceof Number) { if (item.getAcceptedDataTypes().contains(DecimalType.class)) { BigDecimal decimalValue = new BigDecimal(value.toString()).setScale(2, RoundingMode.HALF_UP); context.getEventPublisher().postUpdate(item.getName(), new DecimalType(decimalValue)); } else if (value instanceof Long && item.getAcceptedDataTypes().contains(StringType.class) && "duration".equals(bindingConfig.getProperty())) { // special case, transforming duration to minute:second string context.getEventPublisher().postUpdate(item.getName(), new StringType(durationToString((Long) value))); } else { logger.warn("Unsupported type for item {}, only DecimalType supported!", item.getName()); } } else if (value instanceof String || value instanceof Enum) { if (item.getAcceptedDataTypes().contains(StringType.class)) { if (value instanceof Enum) { String enumValue = WordUtils.capitalizeFully(StringUtils.replace(value.toString(), "_", " ")); context.getEventPublisher().postUpdate(item.getName(), new StringType(enumValue)); } else { context.getEventPublisher().postUpdate(item.getName(), new StringType(value.toString())); } } else { logger.warn("Unsupported type for item {}, only String supported!", item.getName()); } } else { logger.warn("Unsupported value type {}", value.getClass().getSimpleName()); } }
From source file:piuk.blockchain.android.ui.AmountCalculatorFragment.java
private void updateAppearance() { if (exchangeRate != null) { localAmountView.setEnabled(true); final BigDecimal bdExchangeRate = new BigDecimal(exchangeRate); if (exchangeDirection) { final BigInteger btcAmount = btcAmountView.getAmount(); if (btcAmount != null) { localAmountView.setAmount(null); localAmountView.setHint(new BigDecimal(btcAmount).multiply(bdExchangeRate).toBigInteger()); btcAmountView.setHint(null); }/*from w ww. j a va 2 s. c o m*/ } else { final BigInteger localAmount = localAmountView.getAmount(); if (localAmount != null) { btcAmountView.setAmount(null); btcAmountView.setHint(new BigDecimal(localAmount).divide(bdExchangeRate, RoundingMode.HALF_UP) .toBigInteger()); localAmountView.setHint(null); } } } else { localAmountView.setEnabled(false); } }
From source file:net.sourceforge.fenixedu.domain.reports.TutorshipProgramReportFile.java
@Override public void renderReport(final Spreadsheet spreadsheet) throws Exception { spreadsheet.setHeader("Nmero"); spreadsheet.setHeader("Sexo"); spreadsheet.setHeader("Mdia"); spreadsheet.setHeader("Mdia Anual"); spreadsheet.setHeader("Nmero Inscries"); spreadsheet.setHeader("Nmero Aprovaes"); spreadsheet.setHeader("Nota de Seriao"); spreadsheet.setHeader("Local de Origem"); final ExecutionYear executionYear = getExecutionYear(); for (final Degree degree : Degree.readNotEmptyDegrees()) { if (checkDegreeType(getDegreeType(), degree)) { if (isActive(degree)) { for (final Registration registration : degree.getRegistrationsSet()) { if (registration.isRegistered(getExecutionYear())) { int enrolmentCounter = 0; int aprovalCounter = 0; BigDecimal bigDecimal = null; double totalCredits = 0; for (final Registration otherRegistration : registration.getStudent() .getRegistrationsSet()) { if (otherRegistration.getDegree() == registration.getDegree()) { for (final StudentCurricularPlan studentCurricularPlan : otherRegistration .getStudentCurricularPlansSet()) { for (final Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) { final ExecutionSemester executionSemester = enrolment .getExecutionPeriod(); if (executionSemester.getExecutionYear() == executionYear) { enrolmentCounter++; if (enrolment.isApproved()) { aprovalCounter++; final Grade grade = enrolment.getGrade(); if (grade.isNumeric()) { final double credits = enrolment .getEctsCreditsForCurriculum().doubleValue(); totalCredits += credits; bigDecimal = bigDecimal == null ? grade.getNumericValue() .multiply(new BigDecimal(credits)) : bigDecimal.add(grade.getNumericValue() .multiply(new BigDecimal(credits))); } } } }//from w ww.j av a 2s. c om } } } final Row row = spreadsheet.addRow(); row.setCell(registration.getNumber().toString()); row.setCell(registration.getPerson().getGender().toLocalizedString()); row.setCell(registration.getAverage(executionYear)); if (bigDecimal == null) { row.setCell(""); } else { row.setCell( bigDecimal.divide(new BigDecimal(totalCredits), 5, RoundingMode.HALF_UP)); } row.setCell(Integer.toString(enrolmentCounter)); row.setCell(Integer.toString(aprovalCounter)); row.setCell( registration.getEntryGrade() != null ? registration.getEntryGrade().toString() : StringUtils.EMPTY); Boolean dislocated = null; if (registration.getStudentCandidacy() != null) { dislocated = registration.getStudentCandidacy() .getDislocatedFromPermanentResidence(); } final String dislocatedString = dislocated == null ? "" : (dislocated.booleanValue() ? "Deslocado" : "No Deslocado"); row.setCell(dislocatedString); } } } } } }