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:net.sourceforge.subsonic.backend.controller.MultiController.java
private Money getAmountForPeriod(CurrencyUnit currency, Date from, Date to) { List<Money> payments = new ArrayList<Money>(); payments.addAll(paymentDao.getMoneyForPeriod(from, to)); payments.addAll(subscriptionDao.getMoneyForPeriod(from, to)); Map<CurrencyUnit, BigDecimal> currencyConversions = paymentDao.getCurrencyConversionsFor(currency); Money sum = Money.zero(currency);// ww w. j ava 2 s .c o m for (Money payment : payments) { if (currency.equals(payment.getCurrencyUnit())) { sum = sum.plus(payment); } else { BigDecimal conversionRate = currencyConversions.get(payment.getCurrencyUnit()); if (conversionRate == null) { LOG.warn("No conversion rate found for " + currency + " to " + payment.getCurrencyUnit() + ". Skipping it."); } else { sum = sum.plus(payment.convertedTo(currency, conversionRate, RoundingMode.HALF_UP)); } } } return sum; }
From source file:richtercloud.reflection.form.builder.components.AmountMoneyPanel.java
/** * Creates a new AmountMoneyPanel with {@link #DEFAULT_CURRENCIES} and * {@code additionalCurrencies}.//from w ww. jav a 2s . c om * @param amountMoneyCurrencyStorage * @param amountMoneyUsageStatisticsStorage * @param amountMoneyExchangeRateRetriever * @param messageHandler * @throws richtercloud.reflection.form.builder.components.AmountMoneyCurrencyStorageException */ public AmountMoneyPanel(AmountMoneyCurrencyStorage amountMoneyCurrencyStorage, AmountMoneyUsageStatisticsStorage amountMoneyUsageStatisticsStorage, AmountMoneyExchangeRateRetriever amountMoneyExchangeRateRetriever, MessageHandler messageHandler) throws AmountMoneyCurrencyStorageException { this.messageHandler = messageHandler; Set<Currency> exchangeRateRetrieverSupportedCurrencies = amountMoneyExchangeRateRetriever .getSupportedCurrencies(); for (Currency currency : amountMoneyCurrencyStorage.getCurrencies()) { if (!exchangeRateRetrieverSupportedCurrencies.contains(currency)) { try { currency.getExchangeRate(); } catch (ConversionException ex) { throw new IllegalArgumentException(String.format( "Currency %s isn't supported by exchange rate retriever and doesn't have an exchange rate set", currency)); } } currencyComboBoxModel.addElement(currency); } initComponents(); ((SpinnerNumberModel) amountIntegerSpinner.getModel()) .setMaximum(((long) (Double.MAX_VALUE * MINIMAL_STEP))); //cast to long is necessary to make ChangeListener of //amountIntegerSpinner be notified this.amountIntegerSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) { updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue())); } } }); this.amountDecimalSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) { updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue())); } } }); this.currencyComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { //convert after currency change (not necessary, but useful) Currency oldCurrency = (Currency) itemEvent.getItem(); Currency newCurrency = (Currency) itemEvent.getItemSelectable().getSelectedObjects()[0]; double newAmount; try { newAmount = oldCurrency.getConverterTo(newCurrency).convert(getAmount()); } catch (ConversionException ex) { try { //if the exchange rate isn't set AmountMoneyPanel.this.amountMoneyExchangeRateRetriever.retrieveExchangeRate(newCurrency); AmountMoneyPanel.this.amountMoneyExchangeRateRetriever.retrieveExchangeRate(oldCurrency); newAmount = oldCurrency.getConverterTo(newCurrency).convert(getAmount()); } catch (AmountMoneyCurrencyStorageException amountMoneyCurrencyStorageException) { throw new RuntimeException(amountMoneyCurrencyStorageException); } } AmountMoneyPanel.this.amountIntegerSpinner.setValue((int) newAmount); BigDecimal bd = new BigDecimal(newAmount * 100); bd = bd.setScale(0, //newScale RoundingMode.HALF_UP //the rounding mode "taught in school" ); AmountMoneyPanel.this.amountDecimalSpinner.setValue(bd.intValue() % 100); //notify registered update listeners for (AmountMoneyPanelUpdateListener updateListener : AmountMoneyPanel.this.updateListeners) { updateListener.onUpdate(new AmountMoneyPanelUpdateEvent(getValue())); } } }); this.amountMoneyCurrencyStorage = amountMoneyCurrencyStorage; this.amountMoneyUsageStatisticsStorage = amountMoneyUsageStatisticsStorage; this.amountMoneyExchangeRateRetriever = amountMoneyExchangeRateRetriever; }
From source file:org.projectforge.fibu.RechnungDao.java
/** * Sets the scales of percentage and currency amounts. <br/> * Gutschriftsanzeigen drfen keine Rechnungsnummer haben. Wenn eine Rechnungsnummer fr neue Rechnungen gegeben wurde, so muss sie * fortlaufend sein. Berechnet das Zahlungsziel in Tagen, wenn nicht gesetzt, damit es indiziert wird. * @see org.projectforge.core.BaseDao#onSaveOrModify(org.projectforge.core.ExtendedBaseDO) *//* w ww . j a va2s . co m*/ @SuppressWarnings("unchecked") @Override protected void onSaveOrModify(final RechnungDO obj) { if (obj.getTyp() == RechnungTyp.GUTSCHRIFTSANZEIGE_DURCH_KUNDEN) { if (obj.getNummer() != null) { throw new UserException("fibu.rechnung.error.gutschriftsanzeigeDarfKeineRechnungsnummerHaben"); } } else { if (obj.getNummer() == null) { throw new UserException("validation.required.valueNotPresent", new MessageParam("fibu.rechnung.nummer", MessageParamType.I18N_KEY)); } if (obj.getId() == null) { // Neue Rechnung final Integer next = getNextNumber(obj); if (next.intValue() != obj.getNummer().intValue()) { throw new UserException("fibu.rechnung.error.rechnungsNummerIstNichtFortlaufend"); } } else { final List<RechnungDO> list = getHibernateTemplate().find( "from RechnungDO r where r.nummer = ? and r.id <> ?", new Object[] { obj.getNummer(), obj.getId() }); if (list != null && list.size() > 0) { throw new UserException("fibu.rechnung.error.rechnungsNummerBereitsVergeben"); } } } if (obj.getZahlBetrag() != null) { obj.setZahlBetrag(obj.getZahlBetrag().setScale(2, RoundingMode.HALF_UP)); } obj.recalculate(); if (CollectionUtils.isEmpty(obj.getPositionen()) == true) { throw new UserException("fibu.rechnung.error.rechnungHatKeinePositionen"); } final int size = obj.getPositionen().size(); for (int i = size - 1; i > 0; i--) { // Don't remove first position, remove only the last empty positions. final RechnungsPositionDO position = obj.getPositionen().get(i); if (position.getId() == null && position.isEmpty() == true) { obj.getPositionen().remove(i); } else { break; } } writeUiStatusToXml(obj); }
From source file:org.cirdles.ambapo.UTMToLatLong.java
/** * /*from www . ja va 2 s.c om*/ * @param eccentricity * @param currentTau * @param currentSigma * @return change in tau */ private static BigDecimal changeInTau(BigDecimal eccentricity, BigDecimal currentTau, BigDecimal currentSigma) { BigDecimal changeInTau = ((new BigDecimal( Math.sqrt((1 + currentSigma.pow(2).doubleValue()) * (1 + currentTau.pow(2).doubleValue())))) .subtract(currentSigma.multiply(currentTau))) .multiply(new BigDecimal(1 - eccentricity.pow(2).doubleValue())) .multiply(new BigDecimal(Math.sqrt(1 + currentTau.pow(2).doubleValue()))) .divide(BigDecimal.ONE.add(BigDecimal.ONE.subtract(eccentricity.pow(2))) .multiply(currentTau.pow(2)), PRECISION, RoundingMode.HALF_UP); return changeInTau; }
From source file:org.businessmanager.web.controller.page.invoice.InvoiceEditController.java
public BigDecimal getTotalNetPrice() { BigDecimal totalNetPrice = BigDecimal.ZERO; for (LineItemBean lineItem : bean.getLineItems()) { BigDecimal sumPrice = lineItem.getSumPriceNet(); totalNetPrice = totalNetPrice.add(sumPrice); }/*from ww w. j a v a2 s .c o m*/ return totalNetPrice.setScale(2, RoundingMode.HALF_UP); }
From source file:nl.tudelft.stocktrader.derby.DerbyMarketSummaryDAO.java
public void updateStockPriceVolume(double quantity, RemoteQuoteData quote) throws DAOException { // BigDecimal priceChangeFactor = StockTraderUtility.getRandomPriceChangeFactor(quote.getPrice()); // BigDecimal newPrice = quote.getPrice().multiply(priceChangeFactor); ///*from ww w. j av a 2 s .c om*/ // if (newPrice.compareTo(quote.getLow()) == -1) { // quote.setLow(newPrice); // } // if (newPrice.compareTo(quote.getHigh()) == 1) { // quote.setHigh(newPrice); // } PreparedStatement previousValues = null; PreparedStatement updateStockPriceVolumeStat = null; try { previousValues = sqlConnection.prepareStatement(SQL_SELECT_QUOTE); previousValues.setString(1, quote.getTicker()); ResultSet rs = previousValues.executeQuery(); if (!rs.next()) { throw new DAOException("Could not find quote " + quote.getTicker()); } double low = rs.getDouble("low"); double high = rs.getDouble("high"); if (low > quote.getValue()) { low = quote.getValue(); } if (high < quote.getValue()) { high = quote.getValue(); } BigDecimal value = new BigDecimal(quote.getValue()).setScale(4, RoundingMode.HALF_UP); updateStockPriceVolumeStat = sqlConnection.prepareStatement(SQL_UPDATE_STOCKPRICEVOLUME); updateStockPriceVolumeStat.setBigDecimal(1, value); updateStockPriceVolumeStat.setBigDecimal(2, new BigDecimal(low).setScale(4, RoundingMode.HALF_UP)); updateStockPriceVolumeStat.setBigDecimal(3, new BigDecimal(high).setScale(4, RoundingMode.HALF_UP)); updateStockPriceVolumeStat.setBigDecimal(4, value); updateStockPriceVolumeStat.setFloat(5, (float) quantity); updateStockPriceVolumeStat.setString(6, quote.getTicker()); updateStockPriceVolumeStat.executeUpdate(); } catch (SQLException e) { throw new DAOException("", e); } finally { try { if (updateStockPriceVolumeStat != null) { updateStockPriceVolumeStat.close(); } } catch (SQLException e) { logger.debug("", e); } } }
From source file:com.jinhs.fetch.mirror.MirrorClientImpl.java
private void formatLocation(Location location) { double latitude = location.getLatitude(); double longtitude = location.getLongitude(); DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.HALF_UP); latitude = Double.parseDouble(df.format(latitude)); longtitude = Double.parseDouble(df.format(longtitude)); location.setLatitude(latitude);// w w w . j a v a 2 s .c om location.setLongitude(longtitude); }
From source file:com.theaetetuslabs.android_apkmaker.AndroidApkMaker.java
private void makeApk(final NotificationManager mNotifyManager, final NotificationCompat.Builder mBuilder, String projectDirPath, boolean verbose) { ApkMakerOptions options = new ApkMakerOptions(); options.aapt = buildFiles.aapt.getAbsolutePath(); options.androidJar = buildFiles.androidJar.getAbsolutePath(); options.projectDir = projectDirPath; options.outputFile = buildFiles.unsigned.getAbsolutePath(); options.verbose = verbose;//from w w w.j a v a 2s .c om options.aaptRunner = null;/*new AaptRunner(){ @Override public boolean runAapt(File androidManifest, File resourcesArsc, File androidJar, File resDir, File genDir, Callbacks callbacks) { String logDirPath = new File(service.getFilesDir(), "logDir").getAbsolutePath(); Log.d("TAG", "LogDirPath: " + logDirPath); String aaptCommand = "package " + " -f " + //force overwrite existing files; " -v " +//verbose " -M " + androidManifest.getAbsolutePath() + " -F " + resourcesArsc.getAbsolutePath() + //this is where aapt will output the resource file to go in apk " -I " + androidJar.getAbsolutePath() + " -S " + resDir.getAbsolutePath() + " -J " + genDir.getAbsolutePath(); //where to put R.java new TArnAapt(logDirPath).fnExecute(aaptCommand); return false; } };*/ com.theaetetuslabs.java_apkmaker.Main.main(options, null, null, new Callbacks() { @Override public void updateProgress(String msg, float percent) { if (percent == -1) { mBuilder.setProgress(0, 0, true); } else { percent *= 100; mBuilder.setProgress(100, (int) percent, false); DecimalFormat df = new DecimalFormat("##"); df.setRoundingMode(RoundingMode.HALF_UP); msg = msg + ". " + df.format(percent) + "%"; } mBuilder.setContentText(msg); mNotifyManager.notify(ONGOING_NOTIFICATION_ID, mBuilder.build()); } @Override public void error(String str) { sendFailNotification(str); } @Override public void done(File apk) { } }); }
From source file:org.openhab.binding.plex.internal.PlexConnector.java
private String getProgressCommand(PlexBindingConfig config, Command command) { PlexSession session = getSessionByMachineId(config.getMachineIdentifier()); String url = null;/*from w ww.j av a 2 s .c om*/ if (session != null) { int offset = 0; if (command.getClass().equals(PercentType.class)) { PercentType percent = (PercentType) command; offset = new BigDecimal(session.getDuration()).multiply(percent.toBigDecimal() .divide(new BigDecimal("100"), new MathContext(5, RoundingMode.HALF_UP))).intValue(); offset = Math.max(0, offset); offset = Math.min(session.getDuration(), offset); url = String.format("playback/seekTo?offset=%d", offset); } else if (command.getClass().equals(IncreaseDecreaseType.class)) { if (command.equals(IncreaseDecreaseType.DECREASE)) url = PlexBindingConstants.PROPERTY_STEP_BACK; else url = PlexBindingConstants.PROPERTY_STEP_FORWARD; } } return url; }
From source file:org.projectforge.business.fibu.RechnungDao.java
/** * Sets the scales of percentage and currency amounts. <br/> * Gutschriftsanzeigen drfen keine Rechnungsnummer haben. Wenn eine Rechnungsnummer fr neue Rechnungen gegeben * wurde, so muss sie fortlaufend sein. Berechnet das Zahlungsziel in Tagen, wenn nicht gesetzt, damit es indiziert * wird.//from www . ja v a2 s. c om * * @see org.projectforge.framework.persistence.api.BaseDao#onSaveOrModify(org.projectforge.core.ExtendedBaseDO) */ @SuppressWarnings("unchecked") @Override protected void onSaveOrModify(final RechnungDO obj) { if (obj.getTyp() == RechnungTyp.GUTSCHRIFTSANZEIGE_DURCH_KUNDEN) { if (obj.getNummer() != null) { throw new UserException("fibu.rechnung.error.gutschriftsanzeigeDarfKeineRechnungsnummerHaben"); } } else { if (obj.getNummer() == null) { throw new UserException("validation.required.valueNotPresent", new MessageParam("fibu.rechnung.nummer", MessageParamType.I18N_KEY)); } if (obj.getId() == null) { // Neue Rechnung final Integer next = getNextNumber(obj); if (next.intValue() != obj.getNummer().intValue()) { throw new UserException("fibu.rechnung.error.rechnungsNummerIstNichtFortlaufend"); } } else { final List<RechnungDO> list = (List<RechnungDO>) getHibernateTemplate().find( "from RechnungDO r where r.nummer = ? and r.id <> ?", new Object[] { obj.getNummer(), obj.getId() }); if (list != null && list.size() > 0) { throw new UserException("fibu.rechnung.error.rechnungsNummerBereitsVergeben"); } } } if (obj.getZahlBetrag() != null) { obj.setZahlBetrag(obj.getZahlBetrag().setScale(2, RoundingMode.HALF_UP)); } obj.recalculate(); if (CollectionUtils.isEmpty(obj.getPositionen()) == true) { throw new UserException("fibu.rechnung.error.rechnungHatKeinePositionen"); } final int size = obj.getPositionen().size(); for (int i = size - 1; i > 0; i--) { // Don't remove first position, remove only the last empty positions. final RechnungsPositionDO position = obj.getPositionen().get(i); if (position.getId() == null && position.isEmpty() == true) { obj.getPositionen().remove(i); } else { break; } } writeUiStatusToXml(obj); }