java.math.RoundingMode Java Examples
The following examples show how to use
java.math.RoundingMode.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StddevIT.java From phoenix with Apache License 2.0 | 6 votes |
@Test public void testSTDDEV_SAMP() throws Exception { String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), getUrl()); String query = "SELECT STDDEV_SAMP(x_decimal) FROM aTable"; Connection conn = DriverManager.getConnection(getUrl()); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); BigDecimal stddev = rs.getBigDecimal(1); stddev = stddev.setScale(1, RoundingMode.HALF_UP); assertEquals(2.0, stddev.doubleValue(),0.0); assertFalse(rs.next()); } finally { conn.close(); } }
Example #2
Source File: FormatHelper.java From sakai with Educational Community License v2.0 | 6 votes |
private static BigDecimal convertDoubleToBigDecimal(final Double score, final int decimalPlaces) { // Rounding is problematic due to the use of Doubles in // Gradebook. A number like 89.065 (which can be produced by // weighted categories, for example) is stored as the double // 89.06499999999999772626324556767940521240234375. If you // naively round this to two decimal places, you get 89.06 when // you wanted 89.07 // // Payten devised a clever trick of rounding to some larger // decimal places first, which rounds these numbers up to // something more manageable. For example, if you round the // above to 10 places, you get 89.0650000000, which rounds // correctly when rounded up to 2 places. return new BigDecimal(score) .setScale(10, RoundingMode.HALF_UP) .setScale(decimalPlaces, RoundingMode.HALF_UP); }
Example #3
Source File: NativeNumber.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * ECMA 15.7.4.5 Number.prototype.toFixed (fractionDigits) specialized for int fractionDigits * * @param self self reference * @param fractionDigits how many digits should be after the decimal point, 0 if undefined * * @return number in decimal fixed point notation */ @SpecializedFunction public static String toFixed(final Object self, final int fractionDigits) { if (fractionDigits < 0 || fractionDigits > 20) { throw rangeError("invalid.fraction.digits", "toFixed"); } final double x = getNumberValue(self); if (Double.isNaN(x)) { return "NaN"; } if (Math.abs(x) >= 1e21) { return JSType.toString(x); } final NumberFormat format = NumberFormat.getNumberInstance(Locale.US); format.setMinimumFractionDigits(fractionDigits); format.setMaximumFractionDigits(fractionDigits); format.setGroupingUsed(false); format.setRoundingMode(RoundingMode.HALF_UP); return format.format(x); }
Example #4
Source File: StatsItemAggregationEntry.java From java-trader with Apache License 2.0 | 6 votes |
/** * 计算方式: 区间内开始结束两个数据, 计算差值的分钟平均. */ private double getCumulativeAvgValuePerMinute(LinkedList<SampleValueEntry> values, int maxMinutes) { SampleValueEntry lastEntry = values.peekLast(); SampleValueEntry firstEntry = lastEntry; for( Iterator<SampleValueEntry> it=values.descendingIterator(); it.hasNext(); ) { //从后向前逆序 SampleValueEntry entry = it.next(); if ( (lastEntry.getTime()-entry.getTime())>maxMinutes*60 ) { break; } firstEntry = entry; } BigDecimal v = new BigDecimal((lastEntry.getValue()-firstEntry.getValue()), VALUE_CONTEXT); long minutes = ((lastEntry.getTime()-firstEntry.getTime())+30) / 60; if ( minutes<=0 ) { minutes = 1; } BigDecimal av = v.divide(new BigDecimal(minutes), RoundingMode.HALF_UP); return av.doubleValue(); }
Example #5
Source File: PercentileTest.java From phoenix with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testPercentRankWithNegativeNumeric() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, null, getDefaultSplits(tenantId), null, ts); String query = "SELECT PERCENT_RANK(-2) WITHIN GROUP (ORDER BY A_INTEGER ASC) FROM aTable"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at // timestamp 2 Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); BigDecimal rank = rs.getBigDecimal(1); rank = rank.setScale(2, RoundingMode.HALF_UP); assertEquals(0.0, rank.doubleValue(), 0.0); assertFalse(rs.next()); } finally { conn.close(); } }
Example #6
Source File: RoundingHandlersTest.java From mybatis with Apache License 2.0 | 6 votes |
@Test public void shouldInsertUser2() { SqlSession session = sqlSessionFactory.openSession(); try { Mapper mapper = session.getMapper(Mapper.class); User user = new User(); user.setId(2); user.setName("User2"); user.setFunkyNumber(BigDecimal.ZERO); user.setRoundingMode(RoundingMode.UNNECESSARY); mapper.insert(user); mapper.insert2(user); } finally { session.close(); } }
Example #7
Source File: SameObjectDivide.java From Open-Lowcode with Eclipse Public License 2.0 | 6 votes |
@Override public BigDecimal getValueForFormulaInput(E contextobject) { if (((element2.getValueForFormulaInput(contextobject) != null) && (element1.getValueForFormulaInput(contextobject) != null)) && (element2.getValueForFormulaInput(contextobject).compareTo(BigDecimal.ZERO) != 0)) { BigDecimal result = element1.getValueForFormulaInput(contextobject) .divide(element2.getValueForFormulaInput(contextobject), RoundingMode.HALF_DOWN); logger.fine(" Dividing two elements of same object " + contextobject.getName() + " result = " + result); return result; } else { logger.fine(" Division is null as one of the elements is null for " + contextobject.getName()); return null; } }
Example #8
Source File: TestRoundingProvider.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Override public MonetaryAmount apply(MonetaryAmount amount) { MonetaryOperator minorRounding = Monetary .getRounding(RoundingQueryBuilder.of().set("scale", 2).set(RoundingMode.HALF_UP).build()); MonetaryAmount amt = amount.with(minorRounding); MonetaryAmount mp = amt.with(MonetaryOperators.minorPart()); if (mp.isGreaterThanOrEqualTo( Monetary.getDefaultAmountFactory().setCurrency(amount.getCurrency()).setNumber(0.03) .create())) { // add return amt.add(Monetary.getDefaultAmountFactory().setCurrency(amt.getCurrency()) .setNumber(new BigDecimal("0.05")).create().subtract(mp)); } else { // subtract return amt.subtract(mp); } }
Example #9
Source File: StddevTest.java From phoenix with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testSTDDEV_POPOnDecimalColType() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); String query = "SELECT STDDEV_POP(x_decimal) FROM aTable"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at // timestamp 2 Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); BigDecimal stddev = rs.getBigDecimal(1); stddev = stddev.setScale(10, RoundingMode.HALF_UP); assertEquals(1.6679994671, stddev.doubleValue(), 0.0); assertFalse(rs.next()); } finally { conn.close(); } }
Example #10
Source File: MonetaryFormat.java From bcm-android with GNU General Public License v3.0 | 6 votes |
public MonetaryFormat() { // defaults this.negativeSign = '-'; this.positiveSign = 0; // none this.zeroDigit = '0'; this.decimalMark = '.'; this.minDecimals = 2; this.decimalGroups = null; this.shift = 0; this.roundingMode = RoundingMode.HALF_UP; this.codes = new String[MAX_DECIMALS]; this.codes[0] = CODE_BTC; this.codes[3] = CODE_MBTC; this.codes[6] = CODE_UBTC; this.codeSeparator = ' '; this.codePrefixed = true; }
Example #11
Source File: TransactionHistoryFragment.java From guarda-android-wallets with GNU General Public License v3.0 | 6 votes |
private void showBalance() { WalletAPI.getBalance("u"+Coders.md5(sharedManager.getWalletEmail()), Coders.decodeBase64(sharedManager.getLastSyncedBlock()), new Callback<Long>() { @Override public void onResponse(Long balance) { if (balance != null) { try { walletManager.setBalance(new BigDecimal(balance)); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(); symbols.setDecimalSeparator('.'); symbols.setGroupingSeparator(','); DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols); decimalFormat.setRoundingMode(RoundingMode.DOWN); curBalance = decimalFormat.format(WalletAPI.satoshiToCoinsDouble(balance)); setCryptoBalance(curBalance); getLocalBalance(curBalance); } catch (Exception e) { e.printStackTrace(); } } else { ((MainActivity) getActivity()).showCustomToast(getString(R.string.err_get_balance), R.drawable.err_balance); } } }); }
Example #12
Source File: KPIField.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 5 votes |
private final BigDecimal roundToPrecision(final BigDecimal bd) { if (numberPrecision == null) { return bd; } else { return bd.setScale(numberPrecision, RoundingMode.HALF_UP); } }
Example #13
Source File: ParameterPricingData.java From development with Apache License 2.0 | 5 votes |
public BigDecimal getNormalizedTotalCosts() { if (totalCosts == null) { return BigDecimal.ZERO .setScale(PriceConverter.NORMALIZED_PRICE_SCALING); } return totalCosts.setScale(PriceConverter.NORMALIZED_PRICE_SCALING, RoundingMode.HALF_UP); }
Example #14
Source File: InvoiceItem.java From estatio with Apache License 2.0 | 5 votes |
private BigDecimal vatFromNet(final BigDecimal net, final BigDecimal percentage) { if (net == null || percentage == null) { return BigDecimal.ZERO; } BigDecimal rate = percentage.divide(InvoiceConstants.PERCENTAGE_DIVISOR); return net.multiply(rate).setScale(2, RoundingMode.HALF_UP); }
Example #15
Source File: DateTimeFormatterBuilder.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
@Override public boolean format(DateTimePrintContext context, StringBuilder buf) { Long value = context.getValue(field); if (value == null) { return false; } DecimalStyle decimalStyle = context.getDecimalStyle(); BigDecimal fraction = convertToFraction(value); if (fraction.scale() == 0) { // scale is zero if value is zero if (minWidth > 0) { if (decimalPoint) { buf.append(decimalStyle.getDecimalSeparator()); } for (int i = 0; i < minWidth; i++) { buf.append(decimalStyle.getZeroDigit()); } } } else { int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth); fraction = fraction.setScale(outputScale, RoundingMode.FLOOR); String str = fraction.toPlainString().substring(2); str = decimalStyle.convertNumberToI18N(str); if (decimalPoint) { buf.append(decimalStyle.getDecimalSeparator()); } buf.append(str); } return true; }
Example #16
Source File: SellConfirmCoinifyActivity.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
@Override protected void init(Bundle savedInstanceState) { GuardaApp.getAppComponent().inject(this); setToolBarTitle(getString(R.string.toolbar_title_confirm_coinify)); baseAmount = getIntent().getFloatExtra(Extras.COINIFY_IN_AMOUNT, 0.0f); float amountWithCoinifyFee = 0.0f; payMethod = getIntent().getStringExtra(Extras.COINIFY_PAY_METHOD); fee.setText(String.format("%s %s" , getIntent().getStringExtra(Extras.COINIFY_EXCH_FEE), getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT_CUR))); til_coinify_method_fee.setHint(String.format("%s Order", getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT_CUR))); txfee.setText(String.format("%s %s", getIntent().getStringExtra(Extras.COINIFY_COINIFY_FEE), getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT_CUR))); coinify_method_fee.setText(String.format("%s %s", getIntent().getStringExtra(Extras.COINIFY_AMOUNT_RATE), getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT_CUR))); coinify_bank_chb_text.setText(R.string.coinify_sell_confirm); btnNext.setEnabled(false); DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.HALF_EVEN); send.setText(String.format("%s %s", getIntent().getFloatExtra(Extras.COINIFY_IN_AMOUNT, 0.0f), getIntent().getStringExtra(Extras.COINIFY_IN_AMOUNT_CUR))); String tvapx = getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT); received.setText(String.format("%s %s", tvapx, getIntent().getStringExtra(Extras.COINIFY_OUT_AMOUNT_CUR))); email.setText(sharedManager.getCoinifyEmail()); coinify_bank_chb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { btnNext.setEnabled(true); } else { btnNext.setEnabled(false); } } }); }
Example #17
Source File: SimpleNumberFormatterTest.java From super-csv-annotation with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { this.formatter = new SimpleNumberFormatter<>(Double.class, false); this.formatterLenient = new SimpleNumberFormatter<>(Double.class, true); this.formatterPrecision = new SimpleNumberFormatter<>(Double.class, true, new MathContext(4, RoundingMode.DOWN)); }
Example #18
Source File: LongMath.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible // TODO @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log10(long x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); long floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); default: throw new AssertionError(); } }
Example #19
Source File: Convert.java From alpha-wallet-android with MIT License | 5 votes |
public static String getConvertedValue(BigDecimal rawValue, int divisor) { BigDecimal convertedValue = rawValue.divide(new BigDecimal(Math.pow(10, divisor))); DecimalFormat df = new DecimalFormat("0.#####"); df.setRoundingMode(RoundingMode.HALF_DOWN); return df.format(convertedValue); }
Example #20
Source File: DecimalFormat.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Sets the {@link java.math.RoundingMode} used in this DecimalFormat. * * @param roundingMode The <code>RoundingMode</code> to be used * @see #getRoundingMode() * @exception NullPointerException if <code>roundingMode</code> is null. * @since 1.6 */ @Override public void setRoundingMode(RoundingMode roundingMode) { if (roundingMode == null) { throw new NullPointerException(); } this.roundingMode = roundingMode; digitList.setRoundingMode(roundingMode); fastPathCheckNeeded = true; }
Example #21
Source File: BigPerformance.java From winter with Apache License 2.0 | 5 votes |
/** * * @return Returns the Recall */ public double getRecall() { if(correct_total.equals(BigDecimal.ZERO)) { return 0.0; } else { return correct.setScale(getScale()).divide(correct_total, RoundingMode.HALF_UP).doubleValue(); } }
Example #22
Source File: BigDecimalArithmeticTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * round(BigDecimal, MathContext) */ public void testRoundMathContextHALF_UP() { String a = "3736186567876876578956958765675671119238118911893939591735"; int aScale = 45; int precision = 15; RoundingMode rm = RoundingMode.HALF_UP; MathContext mc = new MathContext(precision, rm); String res = "3736186567876.88"; int resScale = 2; BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); BigDecimal result = aNumber.round(mc); assertEquals("incorrect quotient value", res, result.toString()); assertEquals("incorrect quotient scale", resScale, result.scale()); }
Example #23
Source File: MathUtil.java From sailfish-core with Apache License 2.0 | 5 votes |
@Description("Rounds <b>d</b> with specified <b>precision</b><br/>" + "<b>d</b> - double value for rounding<br/>" + "<b>precision</b> - the number of digits after the decimal separator<br/>" + ROUNDING_MODES + "Example:<br/>" + "#{round(5.4564638, 4, \"HALF_UP\")} returns 5.4565") @UtilityMethod public Double round(Double d, int precision, String roundingMode) { BigDecimal bd = BigDecimal.valueOf(d); bd = bd.setScale(precision, RoundingMode.valueOf(roundingMode.toUpperCase())); return bd.doubleValue(); }
Example #24
Source File: DecimalFormat.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Sets the {@link java.math.RoundingMode} used in this DecimalFormat. * * @param roundingMode The <code>RoundingMode</code> to be used * @see #getRoundingMode() * @exception NullPointerException if <code>roundingMode</code> is null. * @since 1.6 */ @Override public void setRoundingMode(RoundingMode roundingMode) { if (roundingMode == null) { throw new NullPointerException(); } this.roundingMode = roundingMode; digitList.setRoundingMode(roundingMode); fastPathCheckNeeded = true; }
Example #25
Source File: Money.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Override public Money multiply(Number multiplicand) { NumberVerifier.checkNoInfinityOrNaN(multiplicand); BigDecimal multiplicandBD = MoneyUtils.getBigDecimal(multiplicand); if (multiplicandBD.equals(BigDecimal.ONE)) { return this; } MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN); BigDecimal dec = this.number.multiply(multiplicandBD, mc); return new Money(dec, getCurrency(), monetaryContext); }
Example #26
Source File: HourWatermark.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions * * @param diffInMilliSecs difference in range * @param hourInterval hour interval (ex: 4 hours) * @param maxIntervals max number of allowed partitions * @return calculated interval in hours */ private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) { int totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING); int totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING); if (totalIntervals > maxIntervals) { hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING); } return Ints.checkedCast(hourInterval); }
Example #27
Source File: PercentileIT.java From phoenix with Apache License 2.0 | 5 votes |
@Test public void testMultiplePercentRanksOnSelect() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, null, getDefaultSplits(tenantId), null, ts); String query = "SELECT PERCENT_RANK(2) WITHIN GROUP (ORDER BY x_decimal ASC), PERCENT_RANK(8.9) WITHIN GROUP (ORDER BY A_INTEGER DESC) FROM aTable"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at // timestamp 2 Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); BigDecimal rank = rs.getBigDecimal(1); rank = rank.setScale(2, RoundingMode.HALF_UP); assertEquals(0.33, rank.doubleValue(), 0.0); rank = rs.getBigDecimal(2); rank = rank.setScale(2, RoundingMode.HALF_UP); assertEquals(0.11, rank.doubleValue(), 0.0); assertFalse(rs.next()); } finally { conn.close(); } }
Example #28
Source File: TradingServiceTest.java From arbitrader with MIT License | 5 votes |
@Test public void testLimitPriceLongSufficientVolume() { BigDecimal allowedVolume = new BigDecimal("1.00"); BigDecimal limitPrice = tradingService.getLimitPrice(longExchange, currencyPair, allowedVolume, Order.OrderType.ASK); assertEquals(new BigDecimal("100.0000").setScale(BTC_SCALE, RoundingMode.HALF_EVEN), limitPrice); }
Example #29
Source File: UserWalletFragment.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
Example #30
Source File: TransactionHistoryFragment.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }