java.math.BigDecimal类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.4k)|赞(0)|评价(0)|浏览(257)

本文整理了Java中java.math.BigDecimal类的一些代码示例,展示了BigDecimal类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BigDecimal类的具体详情如下:
包路径:java.math.BigDecimal
类名称:BigDecimal

BigDecimal介绍

[英]An immutable arbitrary-precision signed decimal.

A value is represented by an arbitrary-precision "unscaled value" and a signed 32-bit "scale", combined thus: unscaled * 10-scale. See #unscaledValue and #scale.

Most operations allow you to supply a MathContext to specify a desired rounding mode.
[中]一种不可变的任意精度有符号十进制数。
值由任意精度的“未标度值”和有符号的32位“标度”表示,组合为:未标度*10标度。参见#无标度值和#标度。
大多数操作允许您提供MathContext来指定所需的舍入模式。

代码示例

代码示例来源:origin: macrozheng/mall

/**
 * 计算总金额
 */
private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
  BigDecimal totalAmount = new BigDecimal("0");
  for (OmsOrderItem item : orderItemList) {
    totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
  }
  return totalAmount;
}

代码示例来源:origin: openhab/openhab1-addons

private PercentType byteToPercentType(int byteValue) {
  BigDecimal percentValue = new BigDecimal(byteValue).multiply(BigDecimal.valueOf(100))
      .divide(BigDecimal.valueOf(255), 2, BigDecimal.ROUND_HALF_UP);
  return new PercentType(percentValue);
}

代码示例来源:origin: prestodb/presto

@Override
public boolean equals(Object o)
{
  if (o == this) return true;
  if (o == null) return false;
  if (o instanceof DecimalNode) {
    return ((DecimalNode) o)._value.compareTo(_value) == 0;
  }
  return false;
}

代码示例来源:origin: stackoverflow.com

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();
}

代码示例来源:origin: stackoverflow.com

new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()

代码示例来源:origin: prestodb/presto

public static int extractNanosecondDecimal(BigDecimal value, long integer)
  {
    // !!! 14-Mar-2016, tatu: Somewhat inefficient; should replace with functionally
    //   equivalent code that just subtracts integral part? (or, measure and show
    //   there's no difference and do nothing... )
    return value.subtract(new BigDecimal(integer)).multiply(ONE_BILLION).intValue();
  }
}

代码示例来源:origin: google/guava

/**
 * Computes the mean in a way that is obvious and resilient to overflow by using BigInteger
 * arithmetic.
 */
private static int computeMeanSafely(int x, int y) {
 BigInteger bigX = BigInteger.valueOf(x);
 BigInteger bigY = BigInteger.valueOf(y);
 BigDecimal bigMean =
   new BigDecimal(bigX.add(bigY)).divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR);
 // parseInt blows up on overflow as opposed to intValue() which does not.
 return Integer.parseInt(bigMean.toString());
}

代码示例来源:origin: prestodb/presto

public static Optional<BigDecimal> fromMetastoreDecimal(@Nullable Decimal decimal)
{
  if (decimal == null) {
    return Optional.empty();
  }
  return Optional.of(new BigDecimal(new BigInteger(decimal.getUnscaled()), decimal.getScale()));
}

代码示例来源:origin: prestodb/presto

@VisibleForTesting
public static BigDecimal average(LongDecimalWithOverflowAndLongState state, DecimalType type)
{
  BigDecimal sum = new BigDecimal(Decimals.decodeUnscaledValue(state.getLongDecimal()), type.getScale());
  BigDecimal count = BigDecimal.valueOf(state.getLong());
  if (state.getOverflow() != 0) {
    BigInteger overflowMultiplier = TWO.shiftLeft(UNSCALED_DECIMAL_128_SLICE_LENGTH * 8 - 2);
    BigInteger overflow = overflowMultiplier.multiply(BigInteger.valueOf(state.getOverflow()));
    sum = sum.add(new BigDecimal(overflow));
  }
  return sum.divide(count, type.getScale(), ROUND_HALF_UP);
}

代码示例来源:origin: google/guava

@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundExactIntegralDoubleToInt() {
 for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
  BigDecimal expected = new BigDecimal(d).setScale(0, UNNECESSARY);
  boolean isInBounds =
    expected.compareTo(MAX_INT_AS_BIG_DECIMAL) <= 0
      & expected.compareTo(MIN_INT_AS_BIG_DECIMAL) >= 0;
  try {
   assertEquals(expected.intValue(), DoubleMath.roundToInt(d, UNNECESSARY));
   assertTrue(isInBounds);
  } catch (ArithmeticException e) {
   assertFalse(isInBounds);
  }
 }
}

代码示例来源:origin: google/guava

@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundExactIntegralDoubleToLong() {
 for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
  // every mode except UNNECESSARY
  BigDecimal expected = new BigDecimal(d).setScale(0, UNNECESSARY);
  boolean isInBounds =
    expected.compareTo(MAX_LONG_AS_BIG_DECIMAL) <= 0
      & expected.compareTo(MIN_LONG_AS_BIG_DECIMAL) >= 0;
  try {
   assertEquals(expected.longValue(), DoubleMath.roundToLong(d, UNNECESSARY));
   assertTrue(isInBounds);
  } catch (ArithmeticException e) {
   assertFalse(isInBounds);
  }
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testBigDecimals() {
  evaluate("3 + new java.math.BigDecimal('5')", new BigDecimal("8"), BigDecimal.class);
  evaluate("3 - new java.math.BigDecimal('5')", new BigDecimal("-2"), BigDecimal.class);
  evaluate("3 * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class);
  evaluate("3 / new java.math.BigDecimal('5')", new BigDecimal("1"), BigDecimal.class);
  evaluate("5 % new java.math.BigDecimal('3')", new BigDecimal("2"), BigDecimal.class);
  evaluate("new java.math.BigDecimal('5') % 3", new BigDecimal("2"), BigDecimal.class);
  evaluate("new java.math.BigDecimal('5') ^ 3", new BigDecimal("125"), BigDecimal.class);
}

代码示例来源:origin: macrozheng/mall

private BigDecimal calcTotalAmount(List<CartPromotionItem> cartItemList) {
  BigDecimal total = new BigDecimal("0");
  for (CartPromotionItem item : cartItemList) {
    BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
    total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
  }
  return total;
}

代码示例来源:origin: prestodb/presto

private static long bigIntegerDecimalToGenericIntegerType(BigInteger bigInteger, int sourceScale, long minValue, long maxValue)
{
  BigDecimal bigDecimal = new BigDecimal(bigInteger, sourceScale);
  BigInteger unscaledValue = bigDecimal.setScale(0, FLOOR).unscaledValue();
  if (unscaledValue.compareTo(BigInteger.valueOf(maxValue)) > 0) {
    return maxValue;
  }
  if (unscaledValue.compareTo(BigInteger.valueOf(minValue)) < 0) {
    return minValue;
  }
  return unscaledValue.longValueExact();
}

代码示例来源:origin: google/guava

/**
 * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code
 * RoundingMode}.
 *
 * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
 *     is not an integer multiple of {@code b}
 */
@GwtIncompatible // TODO
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
 BigDecimal pDec = new BigDecimal(p);
 BigDecimal qDec = new BigDecimal(q);
 return pDec.divide(qDec, 0, mode).toBigIntegerExact();
}

代码示例来源:origin: prestodb/presto

private Optional<DecimalStatistics> buildDecimalStatistics()
{
  if (nonNullValueCount == 0) {
    return Optional.empty();
  }
  return Optional.of(new DecimalStatistics(
      new BigDecimal(BigInteger.valueOf(minimum), scale),
      new BigDecimal(BigInteger.valueOf(maximum), scale),
      SHORT_DECIMAL_VALUE_BYTES));
}

代码示例来源:origin: google/guava

@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundFractionalDoubleToBigInteger() {
 for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
  for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
   BigDecimal expected = new BigDecimal(d).setScale(0, mode);
   assertEquals(expected.toBigInteger(), DoubleMath.roundToBigInteger(d, mode));
  }
 }
}

代码示例来源:origin: google/guava

@GwtIncompatible // TODO
@AndroidIncompatible // TODO(cpovirk): File BigDecimal.divide() rounding bug.
public void testDivNonZero() {
 for (long p : NONZERO_LONG_CANDIDATES) {
  for (long q : NONZERO_LONG_CANDIDATES) {
   for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
    long expected =
      new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).longValue();
    long actual = LongMath.divide(p, q, mode);
    if (expected != actual) {
     failFormat("expected divide(%s, %s, %s) = %s; got %s", p, q, mode, expected, actual);
    }
   }
  }
 }
}

代码示例来源:origin: google/guava

@AndroidIncompatible // slow
public void testDivNonZero() {
 for (int p : NONZERO_INTEGER_CANDIDATES) {
  for (int q : NONZERO_INTEGER_CANDIDATES) {
   for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
    // Skip some tests that fail due to GWT's non-compliant int implementation.
    // TODO(cpovirk): does this test fail for only some rounding modes or for all?
    if (p == -2147483648 && q == -1 && intsCanGoOutOfRange()) {
     continue;
    }
    int expected =
      new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).intValue();
    assertEquals(p + "/" + q, force32(expected), IntMath.divide(p, q, mode));
   }
  }
 }
}

代码示例来源:origin: stackoverflow.com

BigDecimal _0_1 = new BigDecimal(0.1);
BigDecimal x = _0_1;
for(int i = 1; i <= 10; i ++) {
  System.out.println(i+" x 0.1 is "+x+", as double "+x.doubleValue());
  x = x.add(_0_1);
}

相关文章

微信公众号

最新文章

更多