Java Code Examples for java.math.RoundingMode

The following examples show how to use java.math.RoundingMode. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: java-trader   Source File: StatsItemAggregationEntry.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 计算方式: 区间内开始结束两个数据, 计算差值的分钟平均.
 */
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 2
Source Project: Open-Lowcode   Source File: SameObjectDivide.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 3
Source Project: sakai   Source File: FormatHelper.java    License: Educational Community License v2.0 6 votes vote down vote up
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 4
/**
 * 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 5
@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 Project: mybatis   Source File: RoundingHandlersTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: jsr354-ri   Source File: TestRoundingProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: phoenix   Source File: StddevIT.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: phoenix   Source File: StddevTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 Project: bcm-android   Source File: MonetaryFormat.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
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
@Before
public void setUp() throws Exception {
    this.formatter = new SimpleNumberFormatter<>(long.class, false);
    this.formatterLenient = new SimpleNumberFormatter<>(long.class, true);
    this.formatterPrecision = new SimpleNumberFormatter<>(long.class, true, new MathContext(4, RoundingMode.DOWN));
    
}
 
Example 13
@Override
public String getWasApprovedOnMostECTS() {
    BigDecimal lastYearEnrolledECTS = getLastYearEnrolledECTS().setScale(10, RoundingMode.HALF_EVEN);
    BigDecimal lastYearApprovedECTS = getLastYearApprovedECTS().setScale(10, RoundingMode.HALF_EVEN);

    if (lastYearEnrolledECTS.compareTo(new BigDecimal(0)) == 0) {
        return BundleUtil.getString(Bundle.ACADEMIC, "label.no");
    }

    BigDecimal ratio = lastYearApprovedECTS.divide(lastYearEnrolledECTS, RoundingMode.HALF_EVEN);
    return ratio.compareTo(new BigDecimal(0.5f)) == 1 ? BundleUtil.getString(Bundle.ACADEMIC, "label.yes") : BundleUtil
            .getString(Bundle.ACADEMIC, "label.no");
}
 
Example 14
Source Project: codebuff   Source File: BigIntegerMath.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
 * {@code k}, that is, {@code n! / (k! (n - k)!)}.
 *
 * <p><b>Warning:</b> the result can take as much as <i>O(k log n)</i> space.
 *
 * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
 */


public static BigInteger binomial(int n, int k) {
  checkNonNegative("n", n);
  checkNonNegative("k", k);
  checkArgument(k <= n, "k (%s) > n (%s)", k, n);
  if (k > (n >> 1)) {
    k = n - k;
  }
  if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
    return BigInteger.valueOf(LongMath.binomial(n, k));
  }
  BigInteger accum = BigInteger.ONE;
  long numeratorAccum = n;
  long denominatorAccum = 1;
  int bits = LongMath.log2(n, RoundingMode.CEILING);
  int numeratorBits = bits;
  for (int i = 1; i < k; i++) {
    int p = n - i;
    int q = i + 1;

    // log2(p) >= bits - 1, because p >= n/2
    if (numeratorBits + bits >= Long.SIZE - 1) {
      // The numerator is as big as it can get without risking overflow.
      // Multiply numeratorAccum / denominatorAccum into accum.
      accum =
  accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum));
      numeratorAccum = p;
      denominatorAccum = q;
      numeratorBits = bits;
    } else {
      // We can definitely multiply into the long accumulators without overflowing them.
      numeratorAccum *= p;
      denominatorAccum *= q;
      numeratorBits += bits;
    }
  }
  return accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum));
}
 
Example 15
Source Project: codebuff   Source File: LongMath.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 16
Source Project: cashuwallet   Source File: ActivityFragment.java    License: MIT License 5 votes vote down vote up
private String formatAmount(Coin coin, BigInteger amount) {
    //String symbol = coin.getSymbol();
    String code = coin.getCode();
    int decimals = coin.getDecimals();

    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMinimumFractionDigits(decimals);
    format.setMaximumFractionDigits(decimals);
    format.setRoundingMode(RoundingMode.UNNECESSARY);

    BigDecimal decimal = new BigDecimal(amount);
    decimal = decimal.divide(BigDecimal.TEN.pow(decimals));
    String value = format.format(decimal);
    return /*(symbol == null ? "" : symbol + " ") +*/ value + " " + code;
}
 
Example 17
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 18
Source Project: rolling-metrics   Source File: TopMetricSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates new collection of gauges which compatible with {@link com.codahale.metrics.MetricRegistry}.
 *
 * @param name the name prefix for each gauge
 * @param top the target {@link Top}
 * @param latencyUnit the time unit to convert latency
 * @param digitsAfterDecimalPoint the number of digits after decimal point
 */
public TopMetricSet(String name, Top top, TimeUnit latencyUnit, int digitsAfterDecimalPoint) {
    if (name == null) {
        throw new IllegalArgumentException("name should not be null");
    }
    if (name.isEmpty()) {
        throw new IllegalArgumentException("name should not be empty");
    }
    if (top == null) {
        throw new IllegalArgumentException("top should not be null");
    }
    if (latencyUnit == null) {
        throw new IllegalArgumentException("latencyUnit should not be null");
    }
    if (digitsAfterDecimalPoint < 0) {
        throw new IllegalArgumentException("digitsAfterDecimalPoint should not be negative");
    }

    gauges = new HashMap<>();
    gauges.put(name + ".latencyUnit", (Gauge<String>) latencyUnit::toString);

    zero = BigDecimal.ZERO.setScale(digitsAfterDecimalPoint, RoundingMode.CEILING);

    int size = top.getSize();
    for (int i = 0; i < size; i++) {
        String latencyName = name + "." + i + "." + "latency";
        Gauge<BigDecimal> latencyGauge = createLatencyGauge(i, top, latencyUnit, digitsAfterDecimalPoint);
        gauges.put(latencyName, latencyGauge);

        String descriptionName = name + "." + i + "." + "description";
        Gauge<String> descriptionGauge = createDescriptionGauge(i, top);
        gauges.put(descriptionName, descriptionGauge);
    }
}
 
Example 19
private final BigDecimal roundToPrecision(final BigDecimal bd)
{
	if (numberPrecision == null)
	{
		return bd;
	}
	else
	{
		return bd.setScale(numberPrecision, RoundingMode.HALF_UP);
	}
}
 
Example 20
Source Project: alpha-wallet-android   Source File: Convert.java    License: MIT License 5 votes vote down vote up
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 21
Source Project: j2objc   Source File: BigDecimalArithmeticTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Multiply two numbers of different scales using MathContext
 */
public void testMultiplyMathContextDiffScalePosNeg() {
    String a = "987667796597975765768768767866756808779810457634781384756794987";
    int aScale = 100;
    String b = "747233429293018787918347987234564568";
    int bScale = -70;
    String c = "7.3801839465418518653942222612429081498248509257207477E+68";
    int cScale = -16;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    MathContext mc = new MathContext(53, RoundingMode.HALF_UP);
    BigDecimal result = aNumber.multiply(bNumber, mc);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}
 
Example 22
Source Project: scipio-erp   Source File: InvoiceWorker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Gets included tax amount out of Order Adjustments (either from TaxAuthority Services or OrderAdjustment)
 *
 * @param adjustments
 * @return Tax Amount, Zero if there are no adjustments
 * @throws GenericEntityException
 */
public static BigDecimal getTaxAmountIncluded(List<GenericValue> adjustments) throws GenericEntityException {
    BigDecimal taxAmountIncluded = BigDecimal.ZERO;
    for (GenericValue adjustment : adjustments) {
        BigDecimal amountAlreadyIncluded = adjustment.getBigDecimal("amountAlreadyIncluded");
        taxAmountIncluded = taxAmountIncluded.add(amountAlreadyIncluded);
        BigDecimal exemptAmount = adjustment.getBigDecimal("exemptAmount");
        if (exemptAmount != null) {
            taxAmountIncluded = taxAmountIncluded.subtract(exemptAmount);
        }
    }
    return taxAmountIncluded.setScale(2, RoundingMode.HALF_UP);
}
 
Example 23
Source Project: proteus   Source File: Function.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public Value call(Context context, Value data, int dataIndex, Value... arguments) throws Exception {
  double number = Double.parseDouble(arguments[0].getAsString());
  DecimalFormat formatter = getFormatter(arguments);
  formatter.setRoundingMode(RoundingMode.FLOOR);
  formatter.setMinimumFractionDigits(0);
  formatter.setMaximumFractionDigits(2);
  return new Primitive(formatter.format(number));
}
 
Example 24
@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 25
@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 26
@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 27
Source Project: development   Source File: ParameterPricingData.java    License: Apache License 2.0 5 votes vote down vote up
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 28
Source Project: estatio   Source File: InvoiceItem.java    License: Apache License 2.0 5 votes vote down vote up
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 29
Source Project: winter   Source File: BigPerformance.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @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 30
Source Project: j2objc   Source File: BigDecimalArithmeticTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 31
Source Project: sailfish-core   Source File: MathUtil.java    License: Apache License 2.0 5 votes vote down vote up
@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 32
Source Project: openjdk-jdk8u   Source File: DecimalFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 33
Source Project: jsr354-ri   Source File: Money.java    License: Apache License 2.0 5 votes vote down vote up
@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 34
Source Project: incubator-gobblin   Source File: HourWatermark.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 35
Source Project: phoenix   Source File: PercentileIT.java    License: Apache License 2.0 5 votes vote down vote up
@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 36
Source Project: arbitrader   Source File: TradingServiceTest.java    License: MIT License 5 votes vote down vote up
@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 37
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 38
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 39
/**
 * 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 40
Source Project: smarthome   Source File: BinRpcMessage.java    License: Eclipse Public License 2.0 4 votes vote down vote up
private void addObject(Object object) {
    if (object.getClass() == String.class) {
        addInt(3);
        String string = (String) object;
        addInt(string.length());
        addString(string);
    } else if (object.getClass() == Boolean.class) {
        addInt(2);
        addByte(((Boolean) object).booleanValue() ? (byte) 1 : (byte) 0);
    } else if (object.getClass() == Integer.class) {
        addInt(1);
        addInt(((Integer) object).intValue());
    } else if (object.getClass() == Double.class) {
        addInt(4);
        addDouble(((Double) object).doubleValue());
    } else if (object.getClass() == Float.class) {
        addInt(4);
        BigDecimal bd = new BigDecimal((Float) object);
        addDouble(bd.setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigDecimal.class) {
        addInt(4);
        addDouble(((BigDecimal) object).setScale(6, RoundingMode.HALF_DOWN).doubleValue());
    } else if (object.getClass() == BigInteger.class) {
        addInt(4);
        addDouble(((BigInteger) object).doubleValue());
    } else if (object.getClass() == Date.class) {
        addInt(5);
        addInt((int) ((Date) object).getTime() / 1000);
    } else if (object instanceof List<?>) {
        Collection<?> list = (Collection<?>) object;
        addInt(0x100);
        addInt(list.size());
        addList(list);
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;
        addInt(0x101);
        addInt(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            String key = (String) entry.getKey();
            if (key != null) {
                addInt(key.length());
                addString(key);
                addList(Collections.singleton(entry.getValue()));
            }
        }
    }
}