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

The following examples show how to use java.math.BigDecimal#signum() . 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: EventStats.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void addStats(final DebtInterestCalculator calculator) {
    final BigDecimal temp1 = calculator.getDueInterestAmount().add(calculator.getDueFineAmount());
    if (temp1.signum() > 0) {
        debtOverdue = debtOverdue.add(temp1).add(calculator.getDueAmount());
    } else {
        debt = debt.add(calculator.getDueAmount());
    }

    final BigDecimal temp2 = calculator.getPaidInterestAmount().add(calculator.getPaidFineAmount());
    if (temp2.signum() > 0) {
        payedOverdue = payedOverdue.add(temp2);
        payedOverdue.add(calculator.getPaidDebtAmount());
    } else {
        payed = payed.add(calculator.getPaidDebtAmount());
    }

    unused = unused.add(calculator.getPaidUnusedAmount());
    // unused = unused.add(calculator.getTotalUnusedAmount());
}
 
Example 2
Source File: CurrencyValidator.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String text) {
    boolean valid = true;

    if (text.length() > 0) {
        ParsePosition parsePosition = new ParsePosition(0);
        BigDecimal numericAmount = (BigDecimal) FORMAT.parse(text, parsePosition);
        valid = (numericAmount != null &&
            numericAmount.scale() <= 2 &&
            numericAmount.signum() >= 0 &&
            parsePosition.getErrorIndex() == -1 &&
            parsePosition.getIndex() == text.length());
    }

    return valid;
}
 
Example 3
Source File: ParquetValueWriters.java    From iceberg with Apache License 2.0 6 votes vote down vote up
@Override
public void write(int repetitionLevel, BigDecimal decimal) {
  Preconditions.checkArgument(decimal.scale() == scale,
      "Cannot write value as decimal(%s,%s), wrong scale: %s", precision, scale, decimal);
  Preconditions.checkArgument(decimal.precision() <= precision,
      "Cannot write value as decimal(%s,%s), too large: %s", precision, scale, decimal);

  byte fillByte = (byte) (decimal.signum() < 0 ? 0xFF : 0x00);
  byte[] unscaled = decimal.unscaledValue().toByteArray();
  byte[] buf = bytes.get();
  int offset = length - unscaled.length;

  for (int i = 0; i < length; i += 1) {
    if (i < offset) {
      buf[i] = fillByte;
    } else {
      buf[i] = unscaled[i - offset];
    }
  }

  column.writeBinary(repetitionLevel, Binary.fromReusedByteArray(buf));
}
 
Example 4
Source File: BigDecimalMathExperimental.java    From big-math with MIT License 6 votes vote down vote up
public static BigDecimal rootFixPrecision(BigDecimal n, BigDecimal x, MathContext mathContext) {
	switch (x.signum()) {
	case 0:
		return ZERO;
	case -1:
		throw new ArithmeticException("Illegal root(x) for x < 0: x = " + x);
	}

	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);

	BigDecimal factor = ONE.divide(n, mc);
	BigDecimal nMinus1 = n.subtract(ONE);
	BigDecimal result = x.divide(TWO, mc);
	BigDecimal step;

	do {
		step = factor.multiply(x.divide(BigDecimalMath.pow(result, nMinus1, mc), mc).subtract(result, mc), mc);
				
		result = result.add(step, mc);
	} while (step.abs().compareTo(acceptableError) > 0);
	
	return result.round(mathContext);
}
 
Example 5
Source File: LogisticalFormServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<StockMoveLine> getFullySpreadStockMoveLineList(LogisticalForm logisticalForm) {
  List<StockMoveLine> stockMoveLineList = new ArrayList<>();
  Map<StockMoveLine, BigDecimal> spreadableQtyMap = new HashMap<>();

  for (LogisticalForm item : findPendingLogisticalForms(logisticalForm)) {
    spreadableQtyMap.putAll(getSpreadableQtyMap(item));
  }

  for (Entry<StockMoveLine, BigDecimal> entry : spreadableQtyMap.entrySet()) {
    StockMoveLine stockMoveLine = entry.getKey();
    BigDecimal spreadableQty = entry.getValue();

    if (spreadableQty.signum() <= 0) {
      stockMoveLineList.add(stockMoveLine);
    }
  }

  return stockMoveLineList;
}
 
Example 6
Source File: Formatter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void print(BigDecimal value, Locale l) throws IOException {
    if (c == Conversion.HEXADECIMAL_FLOAT)
        failConversion(c, value);
    StringBuilder sb = new StringBuilder();
    boolean neg = value.signum() == -1;
    BigDecimal v = value.abs();
    // leading sign indicator
    leadingSign(sb, neg);

    // the value
    print(sb, v, l, f, c, precision, neg);

    // trailing sign indicator
    trailingSign(sb, neg);

    // justify based on width
    a.append(justify(sb.toString()));
}
 
Example 7
Source File: BigDecimalUtils.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Compute the arctangent of x to a given scale, |x| < 1
 * @param x the value of x
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal arctan(BigDecimal x, int scale)
{
    // Check that |x| < 1.
    if (x.abs().compareTo(BigDecimal.valueOf(1)) >= 0) {
        throw new IllegalArgumentException("|x| >= 1");
    }

    // If x is negative, return -arctan(-x).
    if (x.signum() == -1) {
        return arctan(x.negate(), scale).negate();
    }
    else {
        return arctanTaylor(x, scale);
    }
}
 
Example 8
Source File: LinearCombinationsTest.java    From commons-numbers with Apache License 2.0 6 votes vote down vote up
/**
 * Clip the value to the minimum value that can be stored by a double.
 * Ideally this should round BigDecimal to values occupied by sub-normal numbers.
 * That is non-trivial so this just removes excess precision in the significand and
 * clips it to Double.MIN_VALUE or zero if the value is very small. The ultimate use for
 * the BigDecimal is rounded to the closest double so this method is adequate. It would
 * take many summations of extended precision sub-normal numbers to create more
 * than a few ULP difference to the final double value
 *
 * <p>In data output by the various tests the values have never been known to require
 * clipping so this is just a safety threshold.
 *
 * @param a the value
 * @return the clipped value
 */
private static BigDecimal clip(BigDecimal a) {
    // Min value is approx 4.9e-324. Anything with fewer decimal digits to the right of the
    // decimal point is OK.
    if (a.scale() < 324) {
        return a;
    }
    // Reduce the scale
    final BigDecimal b = a.setScale(MIN.scale(), RoundingMode.HALF_UP);
    // Clip to min value
    final BigDecimal bb = b.abs();
    if (bb.compareTo(MIN) < 0) {
        // Note the number may be closer to MIN than zero so do rounding
        if (MIN.subtract(bb).compareTo(bb) < 0) {
            // Closer to MIN
            return a.signum() == -1 ? MIN.negate() : MIN;
        }
        // Closer to zero
        return BigDecimal.ZERO;
    }
    // Anything above min is allowed.
    return b;
}
 
Example 9
Source File: BigUtils.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the natural logarithm of x to a given scale, x > 0.
 */
public static BigDecimal ln(BigDecimal x, int scale) {
	// Check that x > 0.
	if (x.signum() <= 0) {
		throw new IllegalArgumentException("x <= 0");
	}

	// The number of digits to the left of the decimal point.
	int magnitude = x.toString().length() - x.scale() - 1;

	if (magnitude < 3) {
		return lnNewton(x, scale);
	}

	// Compute magnitude*ln(x^(1/magnitude)).
	else {

		// x^(1/magnitude)
		BigDecimal root = intRoot(x, magnitude, scale);

		// ln(x^(1/magnitude))
		BigDecimal lnRoot = lnNewton(root, scale);

		// magnitude*ln(x^(1/magnitude))
		return BigDecimal.valueOf(magnitude).multiply(lnRoot).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
	}
}
 
Example 10
Source File: StorageStats.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/** %SlotWaste: How well the application data fits in the slots (BytesAppData/(SlotsInUse*AllocatorSize)). */
public float slotWaste() {	
	if (usedStore() == 0)
		return 0.0f;
	
	final BigDecimal size = new BigDecimal(reservedStore());
	final BigDecimal store = new BigDecimal(100 * (reservedStore() - usedStore()));
	if(size.signum()==0) return 0f;
	return store.divide(size, 2, RoundingMode.HALF_UP).floatValue();
}
 
Example 11
Source File: DurationImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>BigInteger value of BigDecimal value.</p>
 *
 * @param value Value to convert.
 * @param canBeNull Can returned value be null?
 *
 * @return BigInteger value of BigDecimal, possibly null.
 */
private static BigInteger toBigInteger(
    BigDecimal value,
    boolean canBeNull) {
    if (canBeNull && value.signum() == 0) {
        return null;
    } else {
        return value.unscaledValue();
    }
}
 
Example 12
Source File: IncomingInvoice.java    From estatio with Apache License 2.0 5 votes vote down vote up
public String validateChangeAmounts(final BigDecimal netAmount, final BigDecimal grossAmount) {
    if ((grossAmount.signum() >= 0 && grossAmount.compareTo(netAmount) < 0) ||
            (grossAmount.signum() < 0 && grossAmount.compareTo(netAmount) > 0)) {
        return "Gross amount cannot be lower than net amount";
    }
    return null;
}
 
Example 13
Source File: Ratio.java    From robozonky with Apache License 2.0 5 votes vote down vote up
public static Ratio fromRaw(final BigDecimal rate) {
    final BigDecimal raw = toScale(rate);
    if (raw.signum() == 0) {
        return ZERO;
    } else if (raw.compareTo(BigDecimal.ONE) == 0) {
        return ONE;
    }
    return new Ratio(raw);
}
 
Example 14
Source File: Numeric.java    From web3j with Apache License 2.0 4 votes vote down vote up
public static boolean isIntegerValue(BigDecimal value) {
    return value.signum() == 0 || value.scale() <= 0 || value.stripTrailingZeros().scale() <= 0;
}
 
Example 15
Source File: Numeric.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public static boolean isIntegerValue(BigDecimal value) {
    return value.signum() == 0
            || value.scale() <= 0
            || value.stripTrailingZeros().scale() <= 0;
}
 
Example 16
Source File: KeyEncoder.java    From Carbonado with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the amount of bytes required to encode a BigDecimal.
 *
 * <p><i>Note:</i> It is recommended that value be normalized by stripping
 * trailing zeros. This makes searching by value much simpler.
 *
 * @param value BigDecimal value to encode, may be null
 * @return amount of bytes needed to encode
 * @since 1.2
 */
public static int calculateEncodedLength(BigDecimal value) {
    if (value == null || value.signum() == 0) {
        return 1;
    }

    return encode(value).mLength;
}
 
Example 17
Source File: Const.java    From pentaho-kettle with Apache License 2.0 3 votes vote down vote up
/**
 * rounds BigDecimal f to any number of places after decimal point Does arithmetic using BigDecimal class to avoid
 * integer overflow while rounding
 *
 * @param f
 *          The value to round
 * @param places
 *          The number of decimal places
 * @param roundingMode
 *          The mode for rounding, e.g. java.math.BigDecimal.ROUND_HALF_EVEN
 * @return The rounded floating point value
 */
public static BigDecimal round( BigDecimal f, int places, int roundingMode ) {
  if ( roundingMode == ROUND_HALF_CEILING ) {
    if ( f.signum() >= 0 ) {
      return round( f, places, BigDecimal.ROUND_HALF_UP );
    } else {
      return round( f, places, BigDecimal.ROUND_HALF_DOWN );
    }
  } else {
    return f.setScale( places, roundingMode );
  }
}
 
Example 18
Source File: BigDecimalCalculations.java    From oopsla15-artifact with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Compute the tangent of x to a given scale, |x| < pi/2
 * 
 * @param x
 *      the value of x  
 * @param scale
 *      the desired scale of the result
 * @return the result value
 */
public static BigDecimal tan(BigDecimal x, int scale) {
	if (x.signum() == 0)
		return BigDecimal.ZERO;
	if (x.abs().compareTo(halfPI) > 0)
		throw new ArithmeticException("x should be between -(pi/2) and (pi/2)");
	// easiest implementation of tan (no need for Bernoulli numbers) but this is slower than the other 2
	return sin(x, scale + 1).divide(cos(x, scale + 1), scale, RoundingMode.HALF_UP);
}
 
Example 19
Source File: BigDecimalUtil.java    From objectlabkit with Apache License 2.0 2 votes vote down vote up
/**
  * @param value the nullable BigDecimal
* @return true if value !=null and &lt; 0.
 */
public static boolean isNegative(final BigDecimal value) {
    return value != null && value.signum() == -1;
}
 
Example 20
Source File: DurationImpl.java    From openjdk-8 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Computes a new duration whose value is <code>factor</code> times
 * longer than the value of this duration.
 *
 * <p>
 * For example,
 * <pre>
 * "P1M" (1 month) * "12" = "P12M" (12 months)
 * "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
 * "P1M" (1 month) * "1.5" = IllegalStateException
 * </pre>
 *
 * <p>
 * Since the {@link Duration} class is immutable, this method
 * doesn't change the value of this object. It simply computes
 * a new Duration object and returns it.
 *
 * <p>
 * The operation will be performed field by field with the precision
 * of {@link BigDecimal}. Since all the fields except seconds are
 * restricted to hold integers,
 * any fraction produced by the computation will be
 * carried down toward the next lower unit. For example,
 * if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
 * which will be carried down to "PT12H" (12 hours).
 * When fractions of month cannot be meaningfully carried down
 * to days, or year to months, this will cause an
 * {@link IllegalStateException} to be thrown.
 * For example if you multiple one month by 0.5.</p>
 *
 * <p>
 * To avoid {@link IllegalStateException}, use
 * the {@link #normalizeWith(Calendar)} method to remove the years
 * and months fields.
 *
 * @param factor to multiply by
 *
 * @return
 *      returns a non-null valid {@link Duration} object
 *
 * @throws IllegalStateException if operation produces fraction in
 * the months field.
 *
 * @throws NullPointerException if the <code>factor</code> parameter is
 * <code>null</code>.
 *
 */
public Duration multiply(BigDecimal factor) {
    BigDecimal carry = ZERO;
    int factorSign = factor.signum();
    factor = factor.abs();

    BigDecimal[] buf = new BigDecimal[6];

    for (int i = 0; i < 5; i++) {
        BigDecimal bd = getFieldAsBigDecimal(FIELDS[i]);
        bd = bd.multiply(factor).add(carry);

        buf[i] = bd.setScale(0, BigDecimal.ROUND_DOWN);

        bd = bd.subtract(buf[i]);
        if (i == 1) {
            if (bd.signum() != 0) {
                throw new IllegalStateException(); // illegal carry-down
            } else {
                carry = ZERO;
            }
        } else {
            carry = bd.multiply(FACTORS[i]);
        }
    }

    if (seconds != null) {
        buf[5] = seconds.multiply(factor).add(carry);
    } else {
        buf[5] = carry;
    }

    return new DurationImpl(
        this.signum * factorSign >= 0,
        toBigInteger(buf[0], null == years),
        toBigInteger(buf[1], null == months),
        toBigInteger(buf[2], null == days),
        toBigInteger(buf[3], null == hours),
        toBigInteger(buf[4], null == minutes),
        (buf[5].signum() == 0 && seconds == null) ? null : buf[5]);
}