List of usage examples for java.math RoundingMode HALF_EVEN
RoundingMode HALF_EVEN
To view the source code for java.math RoundingMode HALF_EVEN.
Click Source Link
From source file:org.hoteia.qalingo.core.domain.CurrencyReferential.java
public NumberFormat getEcoCurrencyformat() { NumberFormat formatter = getStandardCurrencyformat(); formatter.setGroupingUsed(true);// ww w . j av a 2s. co m formatter.setParseIntegerOnly(false); formatter.setRoundingMode(RoundingMode.HALF_EVEN); formatter.setMaximumFractionDigits(2); formatter.setMinimumFractionDigits(2); formatter.setMaximumIntegerDigits(1000000); formatter.setMinimumIntegerDigits(1); return formatter; }
From source file:com.ecrimebureau.File.Hash.java
private byte[] createChecksum(String filename, String algo) throws Exception { InputStream fis = new FileInputStream(filename); byte[] buffer = new byte[1024]; int percentageCompleted; long totalbytes = 0; if (isDirectory == false) { totalbytes = new File(filename).length(); jProgressBar.setMaximum(100);/*from w ww . j a v a 2s .c o m*/ } MessageDigest complete = MessageDigest.getInstance(algo); //One of the following "SHA-1", "SHA-256", "SHA-384", and "SHA-512" int numRead; long readbyte = 0; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); if (isDirectory == false) { DecimalFormat df = new DecimalFormat("0.00"); df.setRoundingMode(RoundingMode.HALF_EVEN); String a = df.format(((readbyte += numRead) * 100.0) / (totalbytes * 2)); percentageCompleted = (int) Math.round(Double.parseDouble(a)); System.out.println(readbyte += numRead); int pervalue = percentageCompleted; if (!(pervalue > 100)) { jProgressBar.setValue(percentageCompleted); jProgressBar.setString(String.valueOf(percentageCompleted) + "%"); } else { jProgressBar.setValue(100); jProgressBar.setString(100 + "%"); } // } } } while (numRead != -1); fis.close(); return complete.digest(); }
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 www.j ava2 s .c om 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.kuali.kpme.core.job.JobBo.java
public void setFte() { if (this.standardHours != null) { this.fte = this.standardHours.divide(new BigDecimal(40)).setScale(2, RoundingMode.HALF_EVEN); } else {/*from w w w . ja v a 2 s . c o m*/ this.fte = new BigDecimal(0).setScale(2); } }
From source file:org.renjin.primitives.MathExt.java
@Builtin @Deferrable/*ww w . j av a2 s . com*/ @DataParallel public static double round(double x, int digits) { // adapted from the nmath library, fround.c double sign; int dig; if (Double.isNaN(x) || Double.isNaN(digits)) { return x + digits; } if (!DoubleVector.isFinite(x)) { return x; } if (digits == Double.POSITIVE_INFINITY) { return x; } else if (digits == Double.NEGATIVE_INFINITY) { return 0.0; } if (digits > MAX_DIGITS) { digits = MAX_DIGITS; } dig = (int) Math.floor(digits + 0.5); if (x < 0.) { sign = -1.; x = -x; } else { sign = 1.; } if (dig == 0) { return sign * Math.rint(x); } else if (dig > 0) { // round to a specific number of decimal places return sign * new BigDecimal(x).setScale(digits, RoundingMode.HALF_EVEN).doubleValue(); } else { // round to the nearest power of 10 double pow10 = Math.pow(10., -dig); return sign * Math.rint(x / pow10) * pow10; } }
From source file:com.icoin.trading.tradeengine.domain.events.trade.TradeExecutedEvent.java
@Override public int hashCode() { return new HashCodeBuilder().append(tradeAmount.toMoney(RoundingMode.HALF_EVEN)) .append(tradedPrice.toMoney(RoundingMode.HALF_EVEN)).append(tradeType).append(buyOrderId) .append(sellOrderId).append(sellTransactionId).append(buyTransactionId).append(orderBookId) .append(coinId).build();//from w ww . ja v a 2 s.c om }
From source file:com.icoin.trading.tradeengine.domain.events.trade.TradeExecutedEvent.java
@Override public String toString() { return "TradeExecutedEvent{" + "tradeAmount=" + tradeAmount.toMoney(RoundingMode.HALF_EVEN) + ", tradedPrice=" + tradedPrice.toMoney(RoundingMode.HALF_EVEN) + ", buyOrderId='" + buyOrderId + '\'' + ", coinId=" + coinId + ", sellOrderId='" + sellOrderId + '\'' + ", buyTransactionId=" + buyTransactionId + ", sellTransactionId=" + sellTransactionId + ", orderBookId=" + orderBookId + ", tradeTime=" + tradeTime + ", tradeType=" + tradeType + ", buyCommission=" + buyCommission.toMoney(RoundingMode.HALF_EVEN) + ", sellCommission=" + sellCommission.toMoney(RoundingMode.HALF_EVEN) + ", executedMoney=" + executedMoney.toMoney(RoundingMode.HALF_EVEN) + '}'; }
From source file:org.wso2.emm.agent.api.DeviceState.java
/** * Returns the string formatted value for the size. * * @param byteValue - Memory in bytes./*from w w w .java 2s .c o m*/ * @return - Memory formatted into GB. */ public double formatSizeInGb(double byteValue) { double gbValue = (byteValue / GB_DIVIDER); BigDecimal roundedValue = new BigDecimal(gbValue).setScale(SCALE, RoundingMode.HALF_EVEN); gbValue = roundedValue.doubleValue(); return gbValue; }
From source file:net.alexjf.tmm.fragments.MoneyNodeEditorFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_moneynode_editor, container, false); nameText = (EditText) v.findViewById(R.id.name_text); descriptionText = (EditText) v.findViewById(R.id.description_text); iconSelectorButton = (SelectorButton) v.findViewById(R.id.icon_selector); creationDateButton = (Button) v.findViewById(R.id.creationDate_button); initialBalanceText = (EditText) v.findViewById(R.id.initialBalance_text); currencySpinner = (Spinner) v.findViewById(R.id.currency_spinner); addButton = (Button) v.findViewById(R.id.add_button); initialBalanceText.setRawInputType(InputType.TYPE_CLASS_NUMBER); FragmentManager fm = getFragmentManager(); datePicker = (DatePickerFragment) fm.findFragmentByTag(TAG_DATEPICKER); iconPicker = (IconPickerFragment) fm.findFragmentByTag(TAG_DRAWABLEPICKER); if (datePicker == null) { datePicker = new DatePickerFragment(); }/*from w w w .jav a 2 s . c o m*/ if (iconPicker == null) { iconPicker = new IconPickerFragment(); } datePicker.setListener(this); iconPicker.setListener(this); creationDateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { try { datePicker.setDate(dateFormat.parse(creationDateButton.getText().toString())); } catch (ParseException e) { } datePicker.show(getFragmentManager(), TAG_DATEPICKER); } }); iconSelectorButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { iconPicker.show(getFragmentManager(), TAG_DRAWABLEPICKER); } }); addButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { if (!validateInputFields()) { return; } String name = nameText.getText().toString().trim(); String description = descriptionText.getText().toString().trim(); Date creationDate; try { creationDate = dateFormat.parse(creationDateButton.getText().toString()); } catch (ParseException e) { creationDate = new Date(); } CurrencyUnit currency = CurrencyUnit .getInstance(currencySpinner.getSelectedItem().toString().trim()); Money initialBalance; try { Calculable calc = new ExpressionBuilder(initialBalanceText.getText().toString()).build(); initialBalance = Money.of(currency, calc.calculate(), RoundingMode.HALF_EVEN); } catch (Exception e) { initialBalance = Money.zero(currency); } if (node == null) { MoneyNode newNode = new MoneyNode(name, description, selectedDrawableName, creationDate, initialBalance, currency); listener.onMoneyNodeCreated(newNode); } else { node.setName(name); node.setIcon(selectedDrawableName); node.setDescription(description); node.setCreationDate(creationDate); node.setInitialBalance(initialBalance); node.setCurrency(currency); listener.onMoneyNodeEdited(node); } } }); if (savedInstanceState != null) { selectedDrawableName = savedInstanceState.getString(KEY_SELECTEDICON); int iconId = DrawableResolver.getInstance().getDrawableId(selectedDrawableName); iconSelectorButton.setDrawableId(iconId); } updateNodeFields(); return v; }
From source file:de.appsolve.padelcampus.utils.BookingUtil.java
public List<TimeSlot> getTimeSlotsForDate(LocalDate selectedDate, List<CalendarConfig> allCalendarConfigs, List<Booking> existingBookings, Boolean onlyFutureTimeSlots, Boolean preventOverlapping) throws CalendarConfigException { List<CalendarConfig> calendarConfigs = calendarConfigUtil.getCalendarConfigsMatchingDate(allCalendarConfigs, selectedDate);/* w w w. ja va 2 s . c o m*/ Iterator<CalendarConfig> iterator = calendarConfigs.iterator(); while (iterator.hasNext()) { CalendarConfig calendarConfig = iterator.next(); if (isHoliday(selectedDate, calendarConfig)) { iterator.remove(); } } List<TimeSlot> timeSlots = new ArrayList<>(); if (calendarConfigs.size() > 0) { LocalDate today = new LocalDate(DEFAULT_TIMEZONE); //sort all calendar configurations for selected date by start time Collections.sort(calendarConfigs); CalendarConfig previousConfig = null; LocalDateTime time = null; LocalDateTime now = new LocalDateTime(DEFAULT_TIMEZONE); //generate list of bookable time slots int i = 0; for (CalendarConfig config : calendarConfigs) { i++; LocalDateTime startDateTime = getLocalDateTime(selectedDate, config.getStartTime()); if (time == null) { //on first iteration time = startDateTime; } else if (!time.plusMinutes(previousConfig.getMinInterval()).equals(startDateTime)) { //reset basePriceLastConfig as this is a non contiguous offer previousConfig = null; time = startDateTime; } LocalDateTime endDateTime = getLocalDateTime(selectedDate, config.getEndTime()); while (time.plusMinutes(config.getMinDuration()).compareTo(endDateTime) <= 0) { BigDecimal pricePerMinDuration; if (previousConfig == null) { pricePerMinDuration = config.getBasePrice(); } else { BigDecimal previousConfigBasePricePerMinute = getPricePerMinute(previousConfig); pricePerMinDuration = previousConfigBasePricePerMinute .multiply(new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128); BigDecimal basePricePerMinute = getPricePerMinute(config); pricePerMinDuration = pricePerMinDuration.add(basePricePerMinute.multiply( new BigDecimal(config.getMinDuration() - previousConfig.getMinInterval()), MathContext.DECIMAL128)); previousConfig = null; } pricePerMinDuration = pricePerMinDuration.setScale(2, RoundingMode.HALF_EVEN); if (onlyFutureTimeSlots) { if (selectedDate.isAfter(today) || time.isAfter(now)) { addTimeSlot(timeSlots, time, config, pricePerMinDuration); } } else { addTimeSlot(timeSlots, time, config, pricePerMinDuration); } time = time.plusMinutes(config.getMinInterval()); } //make sure to display the last min interval of the day if (config.getMinInterval() < config.getMinDuration() && i == calendarConfigs.size()) { if (time.plusMinutes(config.getMinInterval()).compareTo(endDateTime) <= 0) { addTimeSlot(timeSlots, time, config, null); } } previousConfig = config; } //sort time slots by time Collections.sort(timeSlots); //decrease court count for every blocking booking for (TimeSlot timeSlot : timeSlots) { checkForBookedCourts(timeSlot, existingBookings, preventOverlapping); } } return timeSlots; }