List of usage examples for java.math BigDecimal ROUND_HALF_DOWN
int ROUND_HALF_DOWN
To view the source code for java.math BigDecimal ROUND_HALF_DOWN.
Click Source Link
From source file:Main.java
public static void main(String[] args) { BigDecimal bg1 = new BigDecimal("40"); BigDecimal bg2 = new BigDecimal("3"); BigDecimal bg3 = bg1.divide(bg2, BigDecimal.ROUND_HALF_DOWN); System.out.println(bg3);//from w w w . ja v a2s . c om }
From source file:BigDec.java
public static void main(String args[]) { BigDecimal rate = new BigDecimal(".03251234"); BigDecimal months = new BigDecimal("12"); BigDecimal monthlyRate = rate.divide(months, BigDecimal.ROUND_HALF_DOWN); System.out.println("Annual rate : " + rate); System.out.println("Monthly rate: " + monthlyRate); BigDecimal balance = new BigDecimal("10000.0000"); for (int i = 0; i < 12; i++) { BigDecimal interest = balance.multiply(monthlyRate); balance = balance.add(interest); System.out.println("Balance: " + balance); }/*from w ww. j a va 2 s.co m*/ }
From source file:Main.java
public static double round(double unrounded, int precision) { BigDecimal bd = new BigDecimal(unrounded); BigDecimal rounded = bd.setScale(precision, BigDecimal.ROUND_HALF_DOWN); return rounded.doubleValue(); }
From source file:com.haulmont.timesheets.listener.TimeEntryListener.java
protected void setTimeInHours(TimeEntry entity) { BigDecimal minutes = BigDecimal.valueOf(entity.getTimeInMinutes()).setScale(2, BigDecimal.ROUND_HALF_DOWN); entity.setTimeInHours(minutes.divide(MINUTES_IN_HOUR, BigDecimal.ROUND_HALF_DOWN)); }
From source file:com.fusesource.forge.jmstest.executor.BenchmarkJMSProducerWrapper.java
private void runProducers(long rate, long duration) { BigDecimal bd = new BigDecimal(1000000).divide(new BigDecimal(rate), BigDecimal.ROUND_HALF_DOWN); long delayInMicroSeconds; try {//from www .ja v a2s.co m delayInMicroSeconds = bd.longValueExact(); } catch (ArithmeticException e) { delayInMicroSeconds = bd.longValue(); log().warn("Publish rate cannot be expressed as a precise microsecond value, rounding to nearest value " + "[actualDelay: " + delayInMicroSeconds + "]"); } int producersNeeded = (int) (rate / getPartConfig().getMaxConsumerRatePerThread()); if (producersNeeded == 0) { producersNeeded++; } log.debug("Running " + producersNeeded + " producers for " + duration + "s"); producers = new ArrayList<BenchmarkProducer>(producersNeeded); sendingDelay = delayInMicroSeconds * producersNeeded; executor = new ScheduledThreadPoolExecutor(producersNeeded); for (int i = 0; i < producersNeeded; i++) { try { BenchmarkProducer producer = new BenchmarkProducer(this); producer.start(); producer.setMessageCounter(getProbe()); producers.add(producer); } catch (Exception e) { throw new BenchmarkConfigurationException("Unable to create BenchmarkProducer instance", e); } } for (BenchmarkProducer producer : producers) { // TODO should really hold onto these and monitor for failures until the // executor is shutdown executor.scheduleAtFixedRate(new MessageSender(producer), 0, sendingDelay, sendingDelayUnit); } final CountDownLatch latch = new CountDownLatch(1); new ScheduledThreadPoolExecutor(1).schedule(new Runnable() { public void run() { try { log.debug("Shutting down producers."); executor.shutdown(); for (BenchmarkProducer producer : producers) { try { producer.release(); } catch (Exception e) { log().error("Error releasing producer."); } } latch.countDown(); } catch (Exception e) { } } }, duration, TimeUnit.SECONDS); try { latch.await(); } catch (InterruptedException ie) { log().warn("Producer run has been interrupted ..."); } }
From source file:com.silverpeas.util.MetadataExtractor.java
private void computeMp4Duration(Metadata metadata, MovieHeaderBox movieHeaderBox) { BigDecimal duration = BigDecimal.valueOf(movieHeaderBox.getDuration()); if (duration.intValue() > 0) { BigDecimal divisor = BigDecimal.valueOf(movieHeaderBox.getTimescale()); // Duration duration = duration.divide(divisor, 10, BigDecimal.ROUND_HALF_DOWN); // get duration in ms duration = duration.multiply(BigDecimal.valueOf(1000)); metadata.add(XMPDM.DURATION, duration.toString()); }//from ww w.ja v a2s . c om }
From source file:com.twitter.elephantbird.pig.load.HBaseSlice.java
@Override public float getProgress() throws IOException { // No way to know max.. just return 0. Sorry, reporting on the last slice is janky. // So is reporting on the first slice, by the way -- it will start out too high, possibly at 100%. if (endRow_.length == 0) return 0; byte[] lastPadded = m_lastRow_; if (m_lastRow_.length < endRow_.length) { lastPadded = Bytes.padTail(m_lastRow_, endRow_.length - m_lastRow_.length); }/*from w w w . j a v a2 s . c o m*/ if (m_lastRow_.length < startRow_.length) { lastPadded = Bytes.padTail(m_lastRow_, startRow_.length - m_lastRow_.length); } byte[] prependHeader = { 1, 0 }; BigInteger bigLastRow = new BigInteger(Bytes.add(prependHeader, lastPadded)); BigDecimal processed = new BigDecimal(bigLastRow.subtract(bigStart_)); try { BigDecimal progress = processed.setScale(3).divide(bigRange_, BigDecimal.ROUND_HALF_DOWN); return progress.floatValue(); } catch (java.lang.ArithmeticException e) { return 0; } }
From source file:com.silverpeas.notation.model.RatingDAOTest.java
private void assertRatingOnContribution2(ContributionRating contributionRating) { assertThat(contributionRating.getInstanceId(), is(INSTANCE_ID)); assertThat(contributionRating.getContributionType(), is(CONTRIBUTION_TYPE)); assertThat(contributionRating.getContributionId(), is("contribution_2")); assertThat(contributionRating.getRaterRatings().size(), is(3)); assertThat(new BigDecimal("" + contributionRating.getRatingAverage()) .setScale(2, BigDecimal.ROUND_HALF_DOWN).floatValue(), is(3.33F)); UserDetail user1 = aUser("1"); RaterRating rater1Rating = contributionRating.getRaterRating(user1); assertThat(rater1Rating.getRating(), is(contributionRating)); assertThat(rater1Rating.getRater(), is(user1)); assertThat(rater1Rating.getValue(), is(1)); assertThat(rater1Rating.isRatingDone(), is(true)); UserDetail user2 = aUser("2"); RaterRating rater2Rating = contributionRating.getRaterRating(user2); assertThat(rater2Rating.getRating(), is(contributionRating)); assertThat(rater2Rating.getRater(), is(user2)); assertThat(rater2Rating.getValue(), is(5)); assertThat(rater1Rating.isRatingDone(), is(true)); UserDetail user3 = aUser("3"); RaterRating rater3Rating = contributionRating.getRaterRating(user3); assertThat(rater3Rating.getRating(), is(contributionRating)); assertThat(rater3Rating.getRater(), is(user3)); assertThat(rater3Rating.getValue(), is(4)); assertThat(rater1Rating.isRatingDone(), is(true)); }
From source file:Armadillo.Analytics.Base.Precision.java
/** * Rounds the given non-negative value to the "nearest" integer. Nearest is * determined by the rounding method specified. Rounding methods are defined * in {@link BigDecimal}.//from w w w.j ava 2 s . c o m * * @param unscaled Value to round. * @param sign Sign of the original, scaled value. * @param roundingMethod Rounding method, as defined in {@link BigDecimal}. * @return the rounded value. * @throws MathArithmeticException if an exact operation is required but result is not exact * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method. * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0) */ private static double roundUnscaled(double unscaled, double sign, int roundingMethod) throws MathArithmeticException, MathIllegalArgumentException { switch (roundingMethod) { case BigDecimal.ROUND_CEILING: if (sign == -1) { unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); } else { unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); } break; case BigDecimal.ROUND_DOWN: unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); break; case BigDecimal.ROUND_FLOOR: if (sign == -1) { unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); } else { unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY)); } break; case BigDecimal.ROUND_HALF_DOWN: { unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY); double fraction = unscaled - FastMath.floor(unscaled); if (fraction > 0.5) { unscaled = FastMath.ceil(unscaled); } else { unscaled = FastMath.floor(unscaled); } break; } case BigDecimal.ROUND_HALF_EVEN: { double fraction = unscaled - FastMath.floor(unscaled); if (fraction > 0.5) { unscaled = FastMath.ceil(unscaled); } else if (fraction < 0.5) { unscaled = FastMath.floor(unscaled); } else { // The following equality test is intentional and needed for rounding purposes if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even unscaled = FastMath.floor(unscaled); } else { // odd unscaled = FastMath.ceil(unscaled); } } break; } case BigDecimal.ROUND_HALF_UP: { unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY); double fraction = unscaled - FastMath.floor(unscaled); if (fraction >= 0.5) { unscaled = FastMath.ceil(unscaled); } else { unscaled = FastMath.floor(unscaled); } break; } case BigDecimal.ROUND_UNNECESSARY: if (unscaled != FastMath.floor(unscaled)) { throw new MathArithmeticException(); } break; case BigDecimal.ROUND_UP: unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY)); break; default: throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod, "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR", BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN", BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY", BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP); } return unscaled; }
From source file:com.modusoperandi.dragonfly.widgets.map.MapWidgetBMPage.java
@SuppressWarnings("unchecked") private void generateMarkerJs(final SearchResponse results, final StringBuffer markerJs, final String locationField) { for (final SearchHit hit : results.getHits().getHits()) { final GeoPoint location = new GeoPoint(); location.resetFromString(hit.getSource().get(locationField).toString()); final BigDecimal lat = new BigDecimal(location.lat()).setScale(11, BigDecimal.ROUND_HALF_DOWN); final BigDecimal lon = new BigDecimal(location.lon()).setScale(11, BigDecimal.ROUND_HALF_DOWN); markerJs.append("markerLayer.addLayer(L.marker(["); markerJs.append(Double.toString(lat.doubleValue())); markerJs.append(","); markerJs.append(Double.toString(lon.doubleValue())); final StringBuffer markerText = new StringBuffer(); hit.getSource().entrySet().stream().forEach((fields) -> { String markerValue = (String) fields.getValue(); try { markerText.append("<b>"); markerText.append(fields.getKey()); markerText.append(" :</b> "); if (isLink(fields.getKey(), ((Map<String, Object>) typeMappings.get(hit.getType()) .getSourceAsMap().get("_meta")))) { markerText.append("<a href=\""); markerText.append(markerValue); markerText.append("\">"); markerText.append(markerValue); markerText.append("</a>"); } else { if (markerValue.length() > MAX_POPUP_ROW_LENGTH) { markerValue = markerValue.substring(0, MAX_POPUP_ROW_LENGTH) + " ..."; }//from w ww. j av a 2 s. c om markerText.append(StringEscapeUtils.escapeHtml(markerValue).replace('\n', ' ')); } markerText.append("<br>"); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "Cannot access type mappings", e); } catch (final Exception e2) { LOGGER.log(Level.SEVERE, e2.getMessage(), e2); } }); markerJs.append("]).bindPopup('"); markerJs.append(markerText.toString().replace("'", " ")); markerJs.append("', {maxWidth: 500}));\n"); } }