List of usage examples for java.math RoundingMode DOWN
RoundingMode DOWN
To view the source code for java.math RoundingMode DOWN.
Click Source Link
From source file:net.lizalab.util.RdRandRandomTest.java
/** * Runs the Monte Carlo Pi approximation test for the specified * instance of Random./*from w w w .j a v a 2 s.c om*/ * @param random The RNG instance to test. * @param doAssert Flag to indicate whether result should be asserted or simply logged. */ private void monteCarloPiTest(Random random, boolean doAssert) { final String methodName = "monteCarloPiTest : "; int inRandCircle = 0; // xr and yr will be the random point // zr will be the calculated distance to the center double xr, yr, zr; long start = System.currentTimeMillis(); for (int i = 0; i < numPoints; i++) { xr = random.nextDouble(); yr = random.nextDouble(); zr = (xr * xr) + (yr * yr); if (zr <= 1.0) { inRandCircle++; } } long end = System.currentTimeMillis(); LOGGER.info("{} Time: {}ms", methodName, end - start); // calculate the Pi approximations double randomPi = (double) inRandCircle / numPoints * 4.0; // calculate the difference and % error double diff = (randomPi - Math.PI); double randomError = diff / Math.PI * 100; LOGGER.info("{} Pi Approximation: {}, Diff: {}, Error %: {}", methodName, randomPi, diff, randomError); BigDecimal randomPiBD = new BigDecimal(randomPi); randomPiBD = randomPiBD.setScale(precision - 1, RoundingMode.DOWN); // Verify result. boolean result = randomPiBD.compareTo(pi) == 0; String msg = "Pi approximation not sufficiently precise for " + random.getClass(); if (doAssert) { assertTrue(msg, result); } else { if (!result) { LOGGER.warn("{} {}", methodName, msg); } } }
From source file:com.coinblesk.client.utils.UIUtils.java
public static String coinToAmount(Context context, Coin coin) { // transform a given coin value to the "amount string". BigDecimal coinAmount = new BigDecimal(coin.getValue()); BigDecimal div = new BigDecimal(Coin.COIN.getValue()); if (SharedPrefUtils.isBitcoinScaleBTC(context)) { div = new BigDecimal(Coin.COIN.getValue()); } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) { div = new BigDecimal(Coin.MILLICOIN.getValue()); } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) { div = new BigDecimal(Coin.MICROCOIN.getValue()); }/*from w w w. j av a 2s . co m*/ DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.DOWN); df.setMaximumFractionDigits(4); DecimalFormatSymbols decFormat = new DecimalFormatSymbols(); decFormat.setDecimalSeparator('.'); df.setDecimalFormatSymbols(decFormat); String amount = df.format(coinAmount.divide(div)); return amount; }
From source file:com.github.rutvijkumar.twittfuse.Util.java
public static CharSequence formatCount(long count, boolean isUserCount) { // TODO Auto-generated method stub if (count < 1000) { return String.valueOf(count); } else {/*from w ww .java 2 s . com*/ String result = null; NumberFormat df = DecimalFormat.getInstance(); df.setRoundingMode(RoundingMode.DOWN); double countWithK = count / 1000.0; if (isUserCount) { df.setMinimumFractionDigits(0); df.setMaximumFractionDigits(0); } else { df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(1); } result = df.format(countWithK); result = result + "K"; return result; } }
From source file:net.lizalab.util.RdRandRandomTest.java
/** * Tests RdRandRandom using the Monte Carlo Pi approximation test. * Also runs the test for Random and SecureRandom for reference. * @throws GeneralSecurityException //from w ww . j av a2s . c om * @throws SeedException */ @Test public final void testRdRandRandomMonteCarloPi() throws SeedException, GeneralSecurityException { final String methodName = "testRdRandRandomMonteCarloPiTest : "; precision = expectedPrecision(numPoints); // Since the first digit for pi is before the decimal point, we adjust the scale accordingly. pi = pi.setScale(precision - 1, RoundingMode.DOWN); LOGGER.info("{} Generating {} points for Monte Carlo Pi Test. Expected precision: {} digits, {}", methodName, numPoints, precision, pi.toPlainString()); LOGGER.info("{} Running for Random..", methodName); Random random = new Random(); monteCarloPiTest(random, false); LOGGER.info("{} Running for RdRand..", methodName); random = new RdRandRandom(); monteCarloPiTest(random, true); LOGGER.info("{} Running for SecureRandom..", methodName); random = new SecureRandom(); monteCarloPiTest(random, false); LOGGER.info("{} Running Uncommons Maths AESCounterRNG using RdRandSeedGenerator..", methodName); random = new AESCounterRNG(new RdRandSeedGenerator()); monteCarloPiTest(random, false); }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) { if (asset == null) return BigDecimal.ZERO; CoinSparkGenesis genesis = asset.getGenesis(); if (genesis == null) return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated. int chargeBasisPoints = genesis.getChargeBasisPoints(); int chargeExponent = genesis.getChargeFlatExponent(); int chargeMantissa = genesis.getChargeFlatMantissa(); int qtyExponent = genesis.getQtyExponent(); int qtyMantissa = genesis.getQtyMantissa(); double interestRate = asset.getInterestRate(); Date issueDate = asset.getIssueDate(); BigDecimal result = new BigDecimal(rawQuantity.toString()); //System.out.println("interest rate = " + interestRate); //System.out.println("issue date = " + issueDate); //System.out.println("raw units =" + result); // 1. Compute interest if (issueDate != null && interestRate != 0.0) { BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); //interestRate = interestRate / 100; //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString()); // get years elapsed DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); //System.out.println("Issue: " + d1 + " Now: " + d2); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString()); // To avoid exception, we need to set a precision. // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.multiply(new BigDecimal(interestMultipler)); //System.out.println("raw units with interest multiplier =" + result); result = result.setScale(0, RoundingMode.DOWN); //System.out.println("raw units with interest multiplier, floored =" + result); }/* ww w . j a v a 2 s.com*/ // 2. Apply multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); BigDecimal display = result; if (decimalPlaces != 0) { // System.out.println(">>>>> display = " + display.toPlainString()); display = result.movePointLeft(decimalPlaces); // System.out.println(">>>>> display = " + display.toPlainString()); } //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent); // double multiple = asset.getMultiple(); // let's just do it for now to make sure code is corret //if (multiple != 1.0) // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // BigDecimal display = result.multiply(m); //System.out.println("multiplier=" + m + ", display=" + display); // Stripping zeros from internal zero with different scale does not work, so use // JDK bug still seems to exist // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539 // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes int cmpZeroResult = display.compareTo(BigDecimal.ZERO); if (decimalPlaces == 0) { display = display.stripTrailingZeros(); } // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead. if (0 == cmpZeroResult) { display = BigDecimal.ZERO; } return display; }
From source file:it.newfammulfin.api.EntryResource.java
private <K> boolean checkAndBalanceZeroShares(final Map<K, BigDecimal> shares, BigDecimal expectedSum) { if (shares.isEmpty()) { return false; }/*from ww w . j av a2 s . com*/ boolean equalShares = false; if (!Util.containsNotZero(shares.values())) { equalShares = true; expectedSum = expectedSum.setScale(Math.max(DEFAULT_SHARE_SCALE, expectedSum.scale())); for (Map.Entry<K, BigDecimal> shareEntry : shares.entrySet()) { shareEntry.setValue(expectedSum.divide(BigDecimal.valueOf(shares.size()), RoundingMode.DOWN)); } } K largestKey = shares.keySet().iterator().next(); for (Map.Entry<K, BigDecimal> share : shares.entrySet()) { if (share.getValue().abs().compareTo(shares.get(largestKey).abs()) > 0) { largestKey = share.getKey(); } } BigDecimal remainder = Util.remainder(shares.values(), expectedSum); if (remainder.compareTo(BigDecimal.ZERO) != 0) { shares.put(largestKey, shares.get(largestKey).add(remainder)); } return equalShares; }
From source file:no.digipost.print.validate.PdfValidator.java
private double mmToPoints(final int sizeInMillimeters) { BigDecimal points = new BigDecimal(sizeInMillimeters * MM_TO_POINTS); points = points.setScale(1, RoundingMode.DOWN); return points.doubleValue(); }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigInteger getRawUnitsFromDisplayString(CSAsset asset, String display) { BigDecimal result = null;/*from w w w.ja v a2 s . co m*/ try { //System.out.println("Start to get raw units from: " + display); result = new BigDecimal(display); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return null; } // Reverse apply the multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); if (decimalPlaces != 0) { result = result.movePointRight(decimalPlaces); } // FIXME: what if multiple is 0.0? ignore? error? // double multiple = asset.getMultiple(); // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // result = result.divide(m, MathContext.DECIMAL32); //System.out.println("multiplier=" + m + ", removed multiplier =" + display); double interestRate = asset.getInterestRate(); BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); Date issueDate = asset.getIssueDate(); DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.divide(new BigDecimal(String.valueOf(interestMultipler)), MathContext.DECIMAL32); //System.out.println("result = " + result.toPlainString()); result = result.setScale(0, RoundingMode.DOWN); result = result.stripTrailingZeros(); //System.out.println("result floored = " + result.toPlainString()); String resultString = result.toPlainString(); return new BigInteger(resultString); }
From source file:com.norconex.collector.core.crawler.AbstractCrawler.java
private void setProgress(JobStatusUpdater statusUpdater, ICrawlDataStore db) { int queued = db.getQueueSize(); int processed = processedCount; int total = queued + processed; double progress = 0; if (total != 0) { progress = BigDecimal.valueOf(processed) .divide(BigDecimal.valueOf(total), DOUBLE_PROGRESS_SCALE, RoundingMode.DOWN).doubleValue(); }//from w w w.j a va2 s.c om statusUpdater.setProgress(progress); statusUpdater.setNote(NumberFormat.getIntegerInstance().format(processed) + " references processed out of " + NumberFormat.getIntegerInstance().format(total)); if (LOG.isInfoEnabled()) { long currentTime = System.currentTimeMillis(); if (currentTime - lastStatusLoggingTime > STATUS_LOGGING_INTERVAL) { lastStatusLoggingTime = currentTime; int percent = BigDecimal.valueOf(progress).movePointLeft(DOUBLE_PERCENT_SCALE).intValue(); LOG.info( getId() + ": " + percent + "% completed (" + processed + " processed/" + total + " total)"); } } }
From source file:org.ohmage.domain.campaign.prompt.BoundedPrompt.java
/** * Returns whether or not a given value is a whole number. * /*w w w .j a v a 2s. c o m*/ * @param value * The value to check. * * @return True if the BigDecimal is a whole number; false, otherwise. */ protected boolean isWholeNumber(final BigDecimal value) { try { return value.setScale(0, RoundingMode.DOWN).compareTo(value) == 0; } catch (ArithmeticException e) { return false; } }