下面列出了javax.annotation.Nonnegative#java.math.RoundingMode 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 计算方式: 区间内开始结束两个数据, 计算差值的分钟平均.
*/
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();
}
@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;
}
}
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);
}
/**
* 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);
}
@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();
}
}
@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();
}
}
@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);
}
}
@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();
}
}
@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();
}
}
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;
}
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);
}
}
});
}
@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));
}
@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");
}
/**
* 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));
}
/**
* 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();
}
}
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;
}
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();
}
/**
* 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);
}
}
private final BigDecimal roundToPrecision(final BigDecimal bd)
{
if (numberPrecision == null)
{
return bd;
}
else
{
return bd.setScale(numberPrecision, RoundingMode.HALF_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);
}
/**
* 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());
}
/**
* 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);
}
@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));
}
@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));
}
@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);
}
}
});
}
@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;
}
public BigDecimal getNormalizedTotalCosts() {
if (totalCosts == null) {
return BigDecimal.ZERO
.setScale(PriceConverter.NORMALIZED_PRICE_SCALING);
}
return totalCosts.setScale(PriceConverter.NORMALIZED_PRICE_SCALING,
RoundingMode.HALF_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);
}
/**
*
* @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();
}
}
/**
* 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());
}