List of usage examples for java.math BigDecimal divide
public BigDecimal divide(BigDecimal divisor, MathContext mc)
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 va 2 s .c o m return percentageOf; }
From source file:org.estatio.dom.lease.invoicing.InvoiceCalculationService.java
/** * Calculates a term with a given invoicing frequency *///from ww w . j a va 2s . co m @Programmatic public List<CalculationResult> calculateDueDateRange(final LeaseTerm leaseTerm, final InvoiceCalculationParameters parameters) { final List<CalculationResult> results = Lists.newArrayList(); final LocalDateInterval termInterval = leaseTerm.getEffectiveInterval(); final LocalDateInterval rangeInterval = parameters.invoiceRunType().equals(InvoiceRunType.RETRO_RUN) && leaseTerm.getLeaseItem().getLease().getStartDate() .compareTo(parameters.dueDateRange().startDate()) < 0 ? new LocalDateInterval(leaseTerm.getLeaseItem().getLease().getStartDate(), parameters.dueDateRange().endDateExcluding(), IntervalEnding.EXCLUDING_END_DATE) : parameters.dueDateRange(); final InvoicingFrequency invoicingFrequency = leaseTerm.getLeaseItem().getInvoicingFrequency(); // TODO: As a result of EST-413 the check for 'termInterval != null && // termInterval.isValid()' is removed because this is blocking the // calculation of periods outside the interval of the leases. As a // result the invoice calculation will be more eager so improving // performance, EST-315, should get some attention. if (rangeInterval.isValid()) { final List<InvoicingInterval> intervals = invoicingFrequency.intervalsInDueDateRange(rangeInterval, termInterval); for (final InvoicingInterval invoicingInterval : intervals) { final LocalDateInterval effectiveInterval = invoicingInterval.asLocalDateInterval() .overlap(termInterval); if (effectiveInterval == null) { results.add(new CalculationResult(invoicingInterval)); } else { final BigDecimal overlapDays = new BigDecimal(effectiveInterval.days()); final BigDecimal frequencyDays = new BigDecimal(invoicingInterval.days()); final BigDecimal rangeFactor = leaseTerm.valueType().equals(LeaseTermValueType.FIXED) ? BigDecimal.ONE : overlapDays.divide(frequencyDays, MathContext.DECIMAL64); final BigDecimal annualFactor = invoicingFrequency.annualMultiplier(); final LocalDate epochDate = ObjectUtils.firstNonNull(leaseTerm.getLeaseItem().getEpochDate(), systemEpochDate()); BigDecimal mockValue = BigDecimal.ZERO; if (epochDate != null && invoicingInterval.dueDate().isBefore(epochDate)) { mockValue = leaseTerm.valueForDate(epochDate); } results.add(new CalculationResult(invoicingInterval, effectiveInterval, calculateValue(rangeFactor, annualFactor, leaseTerm.valueForDate( parameters.dueDateRange().endDateExcluding().minusDays(1))), calculateValue(rangeFactor, annualFactor, leaseTerm.valueForDate(invoicingInterval.dueDate())), calculateValue(rangeFactor, annualFactor, mockValue))); } } } return results; }
From source file:com.qcadoo.mes.deliveries.DeliveriesServiceImpl.java
private void calculatePriceUsingTotalCost(final ViewDefinitionState view, FieldComponent quantityField, FieldComponent totalPriceField) { FieldComponent pricePerUnitField = (FieldComponent) view.getComponentByReference(L_PRICE_PER_UNIT); Locale locale = view.getLocale(); BigDecimal quantity = getBigDecimalFromField(quantityField, locale); BigDecimal totalPrice = getBigDecimalFromField(totalPriceField, locale); BigDecimal pricePerUnit = numberService .setScale(totalPrice.divide(quantity, numberService.getMathContext())); pricePerUnitField.setFieldValue(numberService.format(pricePerUnit)); pricePerUnitField.requestComponentUpdateState(); }
From source file:de.hybris.platform.b2bacceleratorservices.jalo.promotions.ProductPriceDiscountPromotionByPaymentType.java
@Override public List<PromotionResult> evaluate(final SessionContext ctx, final PromotionEvaluationContext promoContext) { final List<PromotionResult> promotionResults = new ArrayList<PromotionResult>(); // Find all valid products in the cart final PromotionsManager.RestrictionSetResult restrictionResult = this.findEligibleProductsInBasket(ctx, promoContext);/*from w ww. jav a 2 s. co m*/ if (restrictionResult.isAllowedToContinue() && !restrictionResult.getAllowedProducts().isEmpty()) { final PromotionOrderView view = promoContext.createView(ctx, this, restrictionResult.getAllowedProducts()); final AbstractOrder order = promoContext.getOrder(); for (final PromotionOrderEntry entry : view.getAllEntries(ctx)) { // Get the next order entry final long quantityToDiscount = entry.getQuantity(ctx); if (quantityToDiscount > 0) { final long quantityOfOrderEntry = entry.getBaseOrderEntry().getQuantity(ctx).longValue(); // The adjustment to the order entry final double originalUnitPrice = entry.getBasePrice(ctx).doubleValue(); final double originalEntryPrice = quantityToDiscount * originalUnitPrice; final Currency currency = promoContext.getOrder().getCurrency(ctx); Double discountPriceValue; final EnumerationValue paymentType = B2BAcceleratorServicesManager.getInstance() .getPaymentType(ctx, order); if (paymentType != null && StringUtils.equalsIgnoreCase(paymentType.getCode(), getPaymentType().getCode())) { promoContext.startLoggingConsumed(this); discountPriceValue = this.getPriceForOrder(ctx, this.getProductDiscountPrice(ctx), promoContext.getOrder(), ProductPriceDiscountPromotionByPaymentType.PRODUCTDISCOUNTPRICE); final BigDecimal adjustedEntryPrice = Helper.roundCurrencyValue(ctx, currency, originalEntryPrice - (quantityToDiscount * discountPriceValue.doubleValue())); // Calculate the unit price and round it final BigDecimal adjustedUnitPrice = Helper.roundCurrencyValue(ctx, currency, adjustedEntryPrice.equals(BigDecimal.ZERO) ? BigDecimal.ZERO : adjustedEntryPrice.divide(BigDecimal.valueOf(quantityToDiscount), RoundingMode.HALF_EVEN)); for (final PromotionOrderEntryConsumed poec : view.consume(ctx, quantityToDiscount)) { poec.setAdjustedUnitPrice(ctx, adjustedUnitPrice.doubleValue()); } final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx, this, promoContext.getOrder(), 1.0F); result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, true)); final BigDecimal adjustment = Helper.roundCurrencyValue(ctx, currency, adjustedEntryPrice.subtract(BigDecimal.valueOf(originalEntryPrice))); final PromotionOrderEntryAdjustAction poeac = PromotionsManager.getInstance() .createPromotionOrderEntryAdjustAction(ctx, entry.getBaseOrderEntry(), quantityOfOrderEntry, adjustment.doubleValue()); result.addAction(ctx, poeac); promotionResults.add(result); } } } final long remainingCount = view.getTotalQuantity(ctx); if (remainingCount > 0) { promoContext.startLoggingConsumed(this); view.consume(ctx, remainingCount); final PromotionResult result = PromotionsManager.getInstance().createPromotionResult(ctx, this, promoContext.getOrder(), 0.5F); result.setConsumedEntries(ctx, promoContext.finishLoggingAndGetConsumed(this, false)); promotionResults.add(result); } } return promotionResults; }
From source file:org.openhab.binding.wemo.internal.handler.WemoHandler.java
@Override public void onValueReceived(String variable, String value, String service) { logger.debug("Received pair '{}':'{}' (service '{}') for thing '{}'", new Object[] { variable, value, service, this.getThing().getUID() }); updateStatus(ThingStatus.ONLINE);// ww w. j a va2 s .co m this.stateMap.put(variable, value); if (getThing().getThingTypeUID().getId().equals("insight")) { String insightParams = stateMap.get("InsightParams"); if (insightParams != null) { String[] splitInsightParams = insightParams.split("\\|"); if (splitInsightParams[0] != null) { OnOffType binaryState = null; binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState, getThing().getUID()); updateState(CHANNEL_STATE, binaryState); } } long lastChangedAt = 0; try { lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000; // convert s to ms } catch (NumberFormatException e) { logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long", splitInsightParams[1], getThing().getUID()); } ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(lastChangedAt), TimeZone.getDefault().toZoneId()); State lastChangedAtState = new DateTimeType(zoned); if (lastChangedAt != 0) { logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState, getThing().getUID()); updateState(CHANNEL_LASTCHANGEDAT, lastChangedAtState); } State lastOnFor = DecimalType.valueOf(splitInsightParams[2]); if (lastOnFor != null) { logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor, getThing().getUID()); updateState(CHANNEL_LASTONFOR, lastOnFor); } State onToday = DecimalType.valueOf(splitInsightParams[3]); if (onToday != null) { logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday, getThing().getUID()); updateState(CHANNEL_ONTODAY, onToday); } State onTotal = DecimalType.valueOf(splitInsightParams[4]); if (onTotal != null) { logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal, getThing().getUID()); updateState(CHANNEL_ONTOTAL, onTotal); } State timespan = DecimalType.valueOf(splitInsightParams[5]); if (timespan != null) { logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan, getThing().getUID()); updateState(CHANNEL_TIMESPAN, timespan); } State averagePower = DecimalType.valueOf(splitInsightParams[6]); // natively given in W if (averagePower != null) { logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower, getThing().getUID()); updateState(CHANNEL_AVERAGEPOWER, averagePower); } BigDecimal currentMW = new BigDecimal(splitInsightParams[7]); State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (currentPower != null) { logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower, getThing().getUID()); updateState(CHANNEL_CURRENTPOWER, currentPower); } BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]); // recalculate mW-mins to Wh State energyToday = new DecimalType( energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyToday != null) { logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday, getThing().getUID()); updateState(CHANNEL_ENERGYTODAY, energyToday); } BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]); // recalculate mW-mins to Wh State energyTotal = new DecimalType( energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyTotal != null) { logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal, getThing().getUID()); updateState(CHANNEL_ENERGYTOTAL, energyTotal); } BigDecimal standByLimitMW = new BigDecimal(splitInsightParams[10]); State standByLimit = new DecimalType( standByLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (standByLimit != null) { logger.trace("New InsightParam standByLimit '{}' for device '{}' received", standByLimit, getThing().getUID()); updateState(CHANNEL_STANDBYLIMIT, standByLimit); } if (currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue() > standByLimitMW .divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue()) { updateState(CHANNEL_ONSTANDBY, OnOffType.OFF); } else { updateState(CHANNEL_ONSTANDBY, OnOffType.ON); } } } else { State state = stateMap.get("BinaryState").equals("0") ? OnOffType.OFF : OnOffType.ON; logger.debug("State '{}' for device '{}' received", state, getThing().getUID()); if (state != null) { if (getThing().getThingTypeUID().getId().equals("motion")) { updateState(CHANNEL_MOTIONDETECTION, state); if (state.equals(OnOffType.ON)) { State lastMotionDetected = new DateTimeType(); updateState(CHANNEL_LASTMOTIONDETECTED, lastMotionDetected); } } else { updateState(CHANNEL_STATE, state); } } } }
From source file:org.egov.ptis.service.dashboard.PropTaxDashboardService.java
/** * Provides State-wise Collection Statistics for Property Tax, Water Charges and Others * //from w w w . j a v a2 s .c om * @return CollectionStats */ public TotalCollectionStats getTotalCollectionStats(final HttpServletRequest request) { TotalCollectionStats consolidatedCollectionDetails = new TotalCollectionStats(); // For Property Tax collections CollectionStats consolidatedData = new CollectionStats(); Map<String, BigDecimal> consolidatedColl = collectionIndexElasticSearchService .getFinYearsCollByService(COLLECION_BILLING_SERVICE_PT); CFinancialYear currFinYear = getCurrentFinancialYear(); if (!consolidatedColl.isEmpty()) { consolidatedData.setCytdColl(consolidatedColl.get("cytdColln")); consolidatedData.setLytdColl(consolidatedColl.get("lytdColln")); } BigDecimal totalDmd = propertyTaxElasticSearchIndexService.getTotalDemand(); int noOfMonths = DateUtils.noOfMonthsBetween(DateUtils.startOfDay(currFinYear.getStartingDate()), new Date()) + 1; consolidatedData.setTotalDmd(totalDmd.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths))); if (consolidatedData.getTotalDmd().compareTo(BigDecimal.ZERO) > 0) consolidatedData.setPerformance(consolidatedData.getCytdColl().multiply(BIGDECIMAL_100) .divide(consolidatedData.getTotalDmd(), 1, BigDecimal.ROUND_HALF_UP)); if (consolidatedData.getLytdColl().compareTo(BigDecimal.ZERO) > 0) consolidatedData.setLyVar((consolidatedData.getCytdColl().subtract(consolidatedData.getLytdColl()) .multiply(BIGDECIMAL_100)).divide(consolidatedData.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP)); consolidatedCollectionDetails.setPropertyTax(consolidatedData); // For Water Tax collections consolidatedData = new CollectionStats(); consolidatedColl = collectionIndexElasticSearchService .getFinYearsCollByService(COLLECION_BILLING_SERVICE_WTMS); if (!consolidatedColl.isEmpty()) { consolidatedData.setCytdColl(consolidatedColl.get("cytdColln")); consolidatedData.setLytdColl(consolidatedColl.get("lytdColln")); } BigDecimal totalDemandValue = getWaterChargeTotalDemand(request); int numberOfMonths = DateUtils.noOfMonthsBetween(DateUtils.startOfDay(currFinYear.getStartingDate()), new Date()) + 1; consolidatedData.setTotalDmd(totalDemandValue.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(numberOfMonths))); if (consolidatedData.getTotalDmd().compareTo(BigDecimal.ZERO) > 0) consolidatedData.setPerformance(consolidatedData.getCytdColl().multiply(BIGDECIMAL_100) .divide(consolidatedData.getTotalDmd(), 1, BigDecimal.ROUND_HALF_UP)); if (consolidatedData.getLytdColl().compareTo(BigDecimal.ZERO) > 0) consolidatedData.setLyVar((consolidatedData.getCytdColl().subtract(consolidatedData.getLytdColl()) .multiply(BIGDECIMAL_100)).divide(consolidatedData.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP)); consolidatedCollectionDetails.setWaterTax(consolidatedData); // Other collections - temporarily set to 0 consolidatedData = new CollectionStats(); consolidatedData.setCytdColl(BigDecimal.ZERO); consolidatedData.setTotalDmd(BigDecimal.ZERO); consolidatedData.setLytdColl(BigDecimal.ZERO); consolidatedData.setPerformance(BigDecimal.ZERO); consolidatedData.setLyVar(BigDecimal.ZERO); consolidatedCollectionDetails.setOthers(consolidatedData); return consolidatedCollectionDetails; }
From source file:org.eclipse.smarthome.binding.wemo.handler.WemoHandler.java
@Override public void onValueReceived(String variable, String value, String service) { logger.debug("Received pair '{}':'{}' (service '{}') for thing '{}'", new Object[] { variable, value, service, this.getThing().getUID() }); updateStatus(ThingStatus.ONLINE);//w w w . j a v a 2 s . co m this.stateMap.put(variable, value); if (getThing().getThingTypeUID().getId().equals("insight")) { String insightParams = stateMap.get("InsightParams"); if (insightParams != null) { String[] splitInsightParams = insightParams.split("\\|"); if (splitInsightParams[0] != null) { OnOffType binaryState = null; binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState, getThing().getUID()); updateState(CHANNEL_STATE, binaryState); } } long lastChangedAt = 0; try { lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000; // convert s to ms } catch (NumberFormatException e) { logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long", splitInsightParams[1], getThing().getUID()); } GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(lastChangedAt); State lastChangedAtState = new DateTimeType(cal); if (lastChangedAt != 0) { logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState, getThing().getUID()); updateState(CHANNEL_LASTCHANGEDAT, lastChangedAtState); } State lastOnFor = DecimalType.valueOf(splitInsightParams[2]); if (lastOnFor != null) { logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor, getThing().getUID()); updateState(CHANNEL_LASTONFOR, lastOnFor); } State onToday = DecimalType.valueOf(splitInsightParams[3]); if (onToday != null) { logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday, getThing().getUID()); updateState(CHANNEL_ONTODAY, onToday); } State onTotal = DecimalType.valueOf(splitInsightParams[4]); if (onTotal != null) { logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal, getThing().getUID()); updateState(CHANNEL_ONTOTAL, onTotal); } State timespan = DecimalType.valueOf(splitInsightParams[5]); if (timespan != null) { logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan, getThing().getUID()); updateState(CHANNEL_TIMESPAN, timespan); } State averagePower = DecimalType.valueOf(splitInsightParams[6]); // natively given in W if (averagePower != null) { logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower, getThing().getUID()); updateState(CHANNEL_AVERAGEPOWER, averagePower); } BigDecimal currentMW = new BigDecimal(splitInsightParams[7]); State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (currentPower != null) { logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower, getThing().getUID()); updateState(CHANNEL_CURRENTPOWER, currentPower); } BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]); // recalculate mW-mins to Wh State energyToday = new DecimalType( energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyToday != null) { logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday, getThing().getUID()); updateState(CHANNEL_ENERGYTODAY, energyToday); } BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]); // recalculate mW-mins to Wh State energyTotal = new DecimalType( energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP)); if (energyTotal != null) { logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal, getThing().getUID()); updateState(CHANNEL_ENERGYTOTAL, energyTotal); } BigDecimal standByLimitMW = new BigDecimal(splitInsightParams[10]); State standByLimit = new DecimalType( standByLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate // mW to W if (standByLimit != null) { logger.trace("New InsightParam standByLimit '{}' for device '{}' received", standByLimit, getThing().getUID()); updateState(CHANNEL_STANDBYLIMIT, standByLimit); } } } else { State state = stateMap.get("BinaryState").equals("0") ? OnOffType.OFF : OnOffType.ON; logger.debug("State '{}' for device '{}' received", state, getThing().getUID()); if (state != null) { if (getThing().getThingTypeUID().getId().equals("motion")) { updateState(CHANNEL_MOTIONDETECTION, state); if (state.equals(OnOffType.ON)) { State lastMotionDetected = new DateTimeType(); updateState(CHANNEL_LASTMOTIONDETECTED, lastMotionDetected); } } else { updateState(CHANNEL_STATE, state); } } } }
From source file:com.qcadoo.mes.deliveries.DeliveriesServiceImpl.java
private BigDecimal calculatePricePerUnit(final BigDecimal quantity, final BigDecimal totalPrice) { BigDecimal pricePerUnit = BigDecimal.ZERO; if ((quantity == null) || (BigDecimal.ZERO.compareTo(quantity) == 0)) { pricePerUnit = null;/*from w w w. ja va 2 s . c o m*/ } else { pricePerUnit = totalPrice.divide(quantity, numberService.getMathContext()); } return pricePerUnit; }
From source file:org.gradle.performance.measure.DataSeries.java
public DataSeries(Iterable<? extends Amount<Q>> values) { for (Amount<Q> value : values) { if (value != null) { add(value);// ww w . jav a 2s.c om } } if (isEmpty()) { average = null; median = null; max = null; min = null; standardError = null; return; } Amount<Q> total = get(0); Amount<Q> min = get(0); Amount<Q> max = get(0); for (int i = 1; i < size(); i++) { Amount<Q> amount = get(i); total = total.plus(amount); min = min.compareTo(amount) <= 0 ? min : amount; max = max.compareTo(amount) >= 0 ? max : amount; } List<Amount<Q>> sorted = Lists.newArrayList(this); Collections.sort(sorted); Amount<Q> medianLeft = sorted.get((sorted.size() - 1) / 2); Amount<Q> medianRight = sorted.get((sorted.size() - 1) / 2 + 1 - sorted.size() % 2); median = medianLeft.plus(medianRight).div(2); average = total.div(size()); this.min = min; this.max = max; BigDecimal sumSquares = BigDecimal.ZERO; Units<Q> baseUnits = average.getUnits().getBaseUnits(); BigDecimal averageValue = average.toUnits(baseUnits).getValue(); for (int i = 0; i < size(); i++) { Amount<Q> amount = get(i); BigDecimal diff = amount.toUnits(baseUnits).getValue(); diff = diff.subtract(averageValue); diff = diff.multiply(diff); sumSquares = sumSquares.add(diff); } // This isn't quite right, as we may lose precision when converting to a double BigDecimal result = BigDecimal .valueOf(Math .sqrt(sumSquares.divide(BigDecimal.valueOf(size()), RoundingMode.HALF_UP).doubleValue())) .setScale(2, RoundingMode.HALF_UP); standardError = Amount.valueOf(result, baseUnits); }
From source file:org.libreplan.business.orders.daos.OrderElementDAO.java
@Override @Transactional(readOnly = true)// ww w . j a va 2s . c om public BigDecimal getHoursAdvancePercentage(OrderElement orderElement) { boolean condition = orderElement.getSumChargedEffort() != null; final EffortDuration totalChargedEffort = condition ? orderElement.getSumChargedEffort().getTotalChargedEffort() : EffortDuration.zero(); BigDecimal assignedHours = totalChargedEffort.toHoursAsDecimalWithScale(2); BigDecimal estimatedHours = new BigDecimal(orderElement.getWorkHours()).setScale(2); return estimatedHours.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : assignedHours.divide(estimatedHours, RoundingMode.DOWN); }