Java Code Examples for java.math.BigDecimal#negate()

The following examples show how to use java.math.BigDecimal#negate() . 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: UnaryExpression.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private static Number negate(Number left) {
    Class<?> clazz = left.getClass();
    if (clazz == Integer.class) {
        return Integer.valueOf(-left.intValue());
    } else if (clazz == Long.class) {
        return Long.valueOf(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We usually get a big decimal when we have Long.MIN_VALUE constant in
        // the Selector. Long.MIN_VALUE is too big to store in a Long as a positive
        // so we store it as a Big decimal. But it gets Negated right away.. to here
        // we try to covert it back to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 2
Source File: DecimalFormat.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Formats a BigDecimal to produce a string.
 * @param number    The BigDecimal to format
 * @param result    where the text is to be appended
 * @param delegate notified of locations of sub fields
 * @throws           ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @return The formatted number string
 */
StringBuffer format(BigDecimal number, StringBuffer result,
                            FieldDelegate delegate) {
    if (multiplier != 1) {
        number = number.multiply(getBigDecimalMultiplier());
    }
    boolean isNegative = number.signum() == -1;
    if (isNegative) {
        number = number.negate();
    }

    synchronized(digitList) {
        int maxIntDigits = getMaximumIntegerDigits();
        int minIntDigits = getMinimumIntegerDigits();
        int maxFraDigits = getMaximumFractionDigits();
        int minFraDigits = getMinimumFractionDigits();
        int maximumDigits = maxIntDigits + maxFraDigits;

        digitList.set(isNegative, number, useExponentialNotation ?
            ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
            maxFraDigits, !useExponentialNotation);

        return subformat(result, delegate, isNegative, false,
            maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
    }
}
 
Example 3
Source File: BigRational.java    From big-math with MIT License 6 votes vote down vote up
private BigRational(BigDecimal num, BigDecimal denom) {
	BigDecimal n = num;
	BigDecimal d = denom;

	if (d.signum() == 0) {
		throw new ArithmeticException("Divide by zero");
	}

	if (d.signum() < 0) {
		n = n.negate();
		d = d.negate();
	}

	numerator = n;
	denominator = d;
}
 
Example 4
Source File: StatementLine.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
public BigDecimal getSignedAmount() {
    BigDecimal signedAmount = amount;
    if (getDebitCreditMark().sign() < 0) {
        signedAmount = signedAmount.negate();
    }
    if (getDebitCreditType() == DebitCreditType.REVERSAL) {
        signedAmount = signedAmount.negate();
    }
    return signedAmount;
}
 
Example 5
Source File: UnaryExpression.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private static Number negate(Number left) {
    Class clazz = left.getClass();
    if (clazz == Integer.class) {
        return new Integer(-left.intValue());
    } else if (clazz == Long.class) {
        return new Long(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We ussually get a big deciamal when we have Long.MIN_VALUE
        // constant in the
        // Selector. Long.MIN_VALUE is too big to store in a Long as a
        // positive so we store it
        // as a Big decimal. But it gets Negated right away.. to here we try
        // to covert it back
        // to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 6
Source File: UnaryExpression.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static Number negate(Number left) {
   Class clazz = left.getClass();
   if (clazz == Integer.class) {
      return -left.intValue();
   } else if (clazz == Long.class) {
      return -left.longValue();
   } else if (clazz == Float.class) {
      return -left.floatValue();
   } else if (clazz == Double.class) {
      return -left.doubleValue();
   } else if (clazz == BigDecimal.class) {
      // We ussually get a big deciamal when we have Long.MIN_VALUE
      // constant in the
      // Selector. Long.MIN_VALUE is too big to store in a Long as a
      // positive so we store it
      // as a Big decimal. But it gets Negated right away.. to here we try
      // to covert it back
      // to a Long.
      BigDecimal bd = (BigDecimal) left;
      bd = bd.negate();

      if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
         return Long.valueOf(Long.MIN_VALUE);
      }
      return bd;
   } else {
      throw new RuntimeException("Don't know how to negate: " + left);
   }
}
 
Example 7
Source File: WorkflowVentilationServiceSupplychainImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
private PurchaseOrder purchaseOrderLineProcess(Invoice invoice, InvoiceLine invoiceLine)
    throws AxelorException {

  PurchaseOrderLine purchaseOrderLine = invoiceLine.getPurchaseOrderLine();

  if (purchaseOrderLine == null) {
    return null;
  }

  PurchaseOrder purchaseOrder = purchaseOrderLine.getPurchaseOrder();

  BigDecimal invoicedAmountToAdd = invoiceLine.getExTaxTotal();

  // If is it a refund invoice, so we negate the amount invoiced
  if (InvoiceToolService.isRefund(invoiceLine.getInvoice())) {
    invoicedAmountToAdd = invoicedAmountToAdd.negate();
  }

  // Update invoiced amount on purchase order line
  if (!invoice.getCurrency().equals(purchaseOrder.getCurrency())
      && purchaseOrderLine.getCompanyExTaxTotal().compareTo(BigDecimal.ZERO) != 0) {
    // If the purchase order currency is different from the invoice currency, use company currency
    // to calculate a rate. This rate will be applied to purchase order line
    BigDecimal currentCompanyInvoicedAmount = invoiceLine.getCompanyExTaxTotal();
    BigDecimal rate =
        currentCompanyInvoicedAmount.divide(
            purchaseOrderLine.getCompanyExTaxTotal(), 4, RoundingMode.HALF_UP);
    invoicedAmountToAdd = rate.multiply(purchaseOrderLine.getExTaxTotal());
  }

  purchaseOrderLine.setAmountInvoiced(
      purchaseOrderLine.getAmountInvoiced().add(invoicedAmountToAdd));

  return purchaseOrder;
}
 
Example 8
Source File: DurationImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private static void alignSigns(BigDecimal[] buf, int start, int end) {
    // align sign
    boolean touched;

    do { // repeat until all the sign bits become consistent
        touched = false;
        int s = 0; // sign of the left fields

        for (int i = start; i < end; i++) {
            if (s * buf[i].signum() < 0) {
                // this field has different sign than its left field.
                touched = true;

                // compute the number of unit that needs to be borrowed.
                // scale should be 0 in all cases
                BigDecimal borrow = buf[i].abs().divide(
                        FACTORS[i - 1],
                        0,
                        RoundingMode.UP);
                if (buf[i].signum() > 0) {
                    borrow = borrow.negate();
                }

                // update values
                buf[i - 1] = buf[i - 1].subtract(borrow);
                buf[i] = buf[i].add(borrow.multiply(FACTORS[i - 1]));
            }
            if (buf[i].signum() != 0) {
                s = buf[i].signum();
            }
        }
    } while (touched);
}
 
Example 9
Source File: BigDecimalGenerator.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
@Override
public BigDecimal next() {
  BigInteger unscaled =
      BigInteger.valueOf(rng.nextInt((int) Math.pow(10, precision)));
  BigDecimal value = new BigDecimal(unscaled, scale);
  if (rng.nextBoolean()) {
    value = value.negate();
  }
  return value;
}
 
Example 10
Source File: DurationImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Compute <code>value*signum</code> where <code>value==null</code> is treated as <code>value==0</code></p>.
 *
 * @param value Value to sanitize.
 * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
 *
 * @return non-null {@link BigDecimal}.
 */
static BigDecimal sanitize(BigDecimal value, int signum) {
    if (signum == 0 || value == null) {
        return ZERO;
    }
    if (signum > 0) {
        return value;
    }
    return value.negate();
}
 
Example 11
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 5 votes vote down vote up
private CalciteContextException fieldExceedsPrecisionException(
    SqlParserPos pos, int sign, BigDecimal value, TimeUnit type,
    int precision) {
  if (sign == -1) {
    value = value.negate();
  }
  return SqlUtil.newContextException(pos,
      RESOURCE.intervalFieldExceedsPrecision(
          value, type.name() + "(" + precision + ")"));
}
 
Example 12
Source File: UnaryExpression.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
private static Number negate(Number left) {
    Class clazz = left.getClass();
    if (clazz == Integer.class) {
        return new Integer(-left.intValue());
    } else if (clazz == Long.class) {
        return new Long(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We ussually get a big deciamal when we have Long.MIN_VALUE
        // constant in the
        // Selector. Long.MIN_VALUE is too big to store in a Long as a
        // positive so we store it
        // as a Big decimal. But it gets Negated right away.. to here we try
        // to covert it back
        // to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 13
Source File: GammaExperiments.java    From big-math with MIT License 5 votes vote down vote up
public static BigDecimal factorialUsingSpouge(BigDecimal x, MathContext mathContext) {
	// https://en.wikipedia.org/wiki/Spouge%27s_approximation
	MathContext mc = new MathContext(mathContext.getPrecision() * 2, mathContext.getRoundingMode());

	int a = mathContext.getPrecision() * 13 / 10;
	BigDecimal bigA = BigDecimal.valueOf(a);
	BigDecimal c0 = sqrt(pi(mc).multiply(TWO, mc), mc);

	boolean negative = false;
	BigDecimal factor = c0;
	for (int k = 1; k < a; k++) {
		BigDecimal bigK = BigDecimal.valueOf(k);
		BigDecimal ck = pow(BigDecimal.valueOf(a-k), bigK.subtract(BigDecimal.valueOf(0.5), mc), mc);
		ck = ck.multiply(exp(BigDecimal.valueOf(a-k), mc), mc);
		ck = ck.divide(factorial(k - 1), mc);
		if (negative) {
			ck = ck.negate();
		}
		factor = factor.add(ck.divide(x.add(bigK), mc), mc);
		negative = !negative;
	}

	BigDecimal result = pow(x.add(bigA, mc), x.add(BigDecimal.valueOf(0.5), mc), mc);
	result = result.multiply(exp(x.negate().subtract(bigA, mc), mc), mc);
	result = result.multiply(factor, mc);

	return result.round(mathContext);
}
 
Example 14
Source File: DurationImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Compute <code>value*signum</code> where <code>value==null</code> is treated as <code>value==0</code></p>.
 *
 * @param value Value to sanitize.
 * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
 *
 * @return non-null {@link BigDecimal}.
 */
static BigDecimal sanitize(BigDecimal value, int signum) {
    if (signum == 0 || value == null) {
        return ZERO;
    }
    if (signum > 0) {
        return value;
    }
    return value.negate();
}
 
Example 15
Source File: TestOrderedBytes.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * Test encoded value check
 */
@Test
public void testEncodedValueCheck() {
  BigDecimal longMax = BigDecimal.valueOf(Long.MAX_VALUE);
  double negInf = Double.NEGATIVE_INFINITY;
  BigDecimal negLarge = longMax.multiply(longMax).negate();
  BigDecimal negMed = new BigDecimal("-10.0");
  BigDecimal negSmall = new BigDecimal("-0.0010");
  long zero = 0L;
  BigDecimal posSmall = negSmall.negate();
  BigDecimal posMed = negMed.negate();
  BigDecimal posLarge = negLarge.negate();
  double posInf = Double.POSITIVE_INFINITY;
  double nan = Double.NaN;
  byte int8 = 100;
  short int16 = 100;
  int int32 = 100;
  long int64 = 100L;
  float float32 = 100.0f;
  double float64 = 100.0d;
  String text = "hello world.";
  byte[] blobVar = Bytes.toBytes("foo");

  int cnt = 0;
  PositionedByteRange buff = new SimplePositionedMutableByteRange(1024);
  for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
    int o;
    o = OrderedBytes.encodeNull(buff, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negInf, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negLarge, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negMed, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negSmall, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, zero, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posSmall, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posMed, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posLarge, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posInf, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, nan, ord); cnt++;
    o = OrderedBytes.encodeInt8(buff, int8, ord); cnt++;
    o = OrderedBytes.encodeInt16(buff, int16, ord); cnt++;
    o = OrderedBytes.encodeInt32(buff, int32, ord); cnt++;
    o = OrderedBytes.encodeInt64(buff, int64, ord); cnt++;
    o = OrderedBytes.encodeFloat32(buff, float32, ord); cnt++;
    o = OrderedBytes.encodeFloat64(buff, float64, ord); cnt++;
    o = OrderedBytes.encodeString(buff, text, ord); cnt++;
    o = OrderedBytes.encodeBlobVar(buff, blobVar, ord); cnt++;
  }

  buff.setPosition(0);
  assertEquals(OrderedBytes.length(buff), cnt);
  for (int i = 0; i < cnt; i++) {
    assertTrue(OrderedBytes.isEncodedValue(buff));
    OrderedBytes.skip(buff);
  }
}
 
Example 16
Source File: QuoinexOrder.java    From cryptotrader with GNU Affero General Public License v3.0 4 votes vote down vote up
@VisibleForTesting
BigDecimal convertQuantity(BigDecimal value) {

    if (value != null) {

        if ("buy".equals(side)) {
            return value;
        }

        if ("sell".equals(side)) {
            return value.negate();
        }

    }

    return null;

}
 
Example 17
Source File: BitbankContext.java    From cryptotrader with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public BigDecimal getConversionPrice(Key key, CurrencyType currency) {

    if (currency == null) {
        return null;
    }

    if (currency == getInstrumentCurrency(key)) {
        return ONE;
    }

    if (currency == getFundingCurrency(key)) {

        BigDecimal p = getMidPrice(key);

        return p == null ? null : p.negate();

    }

    return null;

}
 
Example 18
Source File: R238_236oc.java    From ET_Redux with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param inputValueModels
 * @param parDerivTerms
 */
@Override
public void calculateValue (
        ValueModel[] inputValueModels,
        ConcurrentMap<String, BigDecimal> parDerivTerms ) {

    r18O_16O = inputValueModels[0];
    r270_268m = inputValueModels[1];

    BigDecimal BD2 = new BigDecimal( 2.0 );


    setValue(//
            r270_268m.getValue().//
            subtract( BD2.//
            multiply( r18O_16O.getValue() ) ) );



    BigDecimal dR238_236oc__dR270_268m = BigDecimal.ONE;
    parDerivTerms.put( "dR238_236oc__dR270_268m", dR238_236oc__dR270_268m );

    BigDecimal dR238_236oc__dR18O_16O = BD2.negate();
    parDerivTerms.put( "dR238_236oc__dR18O_16O", dR238_236oc__dR18O_16O );

}
 
Example 19
Source File: BasicBigDecimal.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private static BigDecimal negate(BigDecimal v) {
    return v.negate();
}
 
Example 20
Source File: FiscoContext.java    From cryptotrader with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public BigDecimal getConversionPrice(Key key, CurrencyType currency) {

    if (currency == null) {
        return null;
    }

    if (currency == getInstrumentCurrency(key)) {
        return ONE;
    }

    if (currency == getFundingCurrency(key)) {

        BigDecimal p = getMidPrice(key);

        return p == null ? null : p.negate();

    }

    return null;

}