Tabnine Logo
BigDecimal
Code IndexAdd Tabnine to your IDE (free)

How to use
BigDecimal
in
java.math

Best Java code snippets using java.math.BigDecimal (Showing top 20 results out of 42,390)

Refine searchRefine arrow

  • BigInteger
  • Date
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);
}
java.mathBigDecimal

Javadoc

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.

Most used methods

  • <init>
    Translates a character array representation of a BigDecimal into a BigDecimal, accepting the same se
  • valueOf
  • compareTo
    Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in val
  • doubleValue
    Converts this BigDecimal to a double. This conversion is similar to thenarrowing primitive conversio
  • setScale
    Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by m
  • divide
  • add
  • multiply
  • toString
    Returns the string representation of this BigDecimal, using scientific notation if an exponent is ne
  • subtract
    Returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context sett
  • intValue
    Converts this BigDecimal to an int. This conversion is analogous to thenarrowing primitive conversio
  • longValue
    Converts this BigDecimal to a long. This conversion is analogous to thenarrowing primitive conversio
  • intValue,
  • longValue,
  • toPlainString,
  • scale,
  • toBigInteger,
  • equals,
  • floatValue,
  • negate,
  • unscaledValue,
  • abs

Popular in Java

  • Reading from database using SQL prepared statement
  • findViewById (Activity)
  • addToBackStack (FragmentTransaction)
  • scheduleAtFixedRate (ScheduledExecutorService)
  • Container (java.awt)
    A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT co
  • Rectangle (java.awt)
    A Rectangle specifies an area in a coordinate space that is enclosed by the Rectangle object's top-
  • File (java.io)
    An "abstract" representation of a file system entity identified by a pathname. The pathname may be a
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • PrintWriter (java.io)
    Wraps either an existing OutputStream or an existing Writerand provides convenience methods for prin
  • TimeUnit (java.util.concurrent)
    A TimeUnit represents time durations at a given unit of granularity and provides utility methods to
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now