/** Constructs a new BigFraction from the given BigDecimal object. */ public BigFraction(BigDecimal d) { this( d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(), d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale())); }
public Money getAdjustmentPrice() { return adjustmentPrice == null ? null : new Money( adjustmentPrice, delegate.getSubTotal().getCurrency(), adjustmentPrice.scale() == 0 ? BankersRounding.DEFAULT_SCALE : adjustmentPrice.scale()); }
private BigDecimal fixBigDecimal(BigDecimal val) { if (val.scale() > 0) { val = val.stripTrailingZeros(); if (val.scale() < 0) { val = val.setScale(0); } } return val; }
@Override protected <T> String internalValueToString( final T value, final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale, final Boolean isUnicode) throws EdmPrimitiveTypeException { String result; if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte || value instanceof BigInteger) { result = value.toString(); final int digits = result.startsWith("-") ? result.length() - 1 : result.length(); if (precision != null && precision < digits) { throw new EdmPrimitiveTypeException( "The value '" + value + "' does not match the facets' constraints."); } } else if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { BigDecimal bigDecimalValue; try { bigDecimalValue = value instanceof Double ? BigDecimal.valueOf((Double) value) : value instanceof Float ? BigDecimal.valueOf((Float) value) : (BigDecimal) value; } catch (final NumberFormatException e) { throw new EdmPrimitiveTypeException("The value '" + value + "' is not valid.", e); } final int digits = bigDecimalValue.scale() >= 0 ? Math.max(bigDecimalValue.precision(), bigDecimalValue.scale()) : bigDecimalValue.precision() - bigDecimalValue.scale(); if ((precision == null || precision >= digits) && (bigDecimalValue.scale() <= (scale == null ? 0 : scale))) { result = bigDecimalValue.toPlainString(); } else { throw new EdmPrimitiveTypeException( "The value '" + value + "' does not match the facets' constraints."); } } else { throw new EdmPrimitiveTypeException( "The value type " + value.getClass() + " is not supported."); } return result; }
/** @throws Exception */ public void testGetBigDecimal() throws Exception { MockResultSet rs = new MockResultSet(); ArrayMap rowData = new ArrayMap(); BigDecimal value = new BigDecimal(1); rowData.put("id", value); rs.addRowData(rowData); assertTrue(rs.next()); assertEquals(value, rs.getBigDecimal(1)); assertEquals(value, rs.getBigDecimal("id")); BigDecimal value2 = rs.getBigDecimal(1, 2); assertEquals(2, value2.scale()); value2 = rs.getBigDecimal("id", 2); assertEquals(2, value2.scale()); }
/** * Constructs a new BigFraction from two BigDecimals. * * @throws ArithemeticException if denominator == 0. */ private static BigFraction valueOfHelper( final BigDecimal numerator, final BigDecimal denominator) { // Note: Cannot use .equals(BigDecimal.ZERO), because "0.00" != "0.0". if (denominator.unscaledValue().equals(BigInteger.ZERO)) { throw new ArithmeticException("Divide by zero: fraction denominator is zero."); } // Format of BigDecimal: unscaled / 10^scale BigInteger tmpNumerator = numerator.unscaledValue(); BigInteger tmpDenominator = denominator.unscaledValue(); // (u1/10^s1) / (u2/10^s2) = u1 / (u2 * 10^(s1-s2)) = (u1 * 10^(s2-s1)) // / u2 if (numerator.scale() > denominator.scale()) { tmpDenominator = tmpDenominator.multiply(BigInteger.TEN.pow(numerator.scale() - denominator.scale())); } else if (numerator.scale() < denominator.scale()) { tmpNumerator = tmpNumerator.multiply(BigInteger.TEN.pow(denominator.scale() - numerator.scale())); // else: scales are equal, do nothing. } final BigInteger gcd = tmpNumerator.gcd(tmpDenominator); tmpNumerator = tmpNumerator.divide(gcd); tmpDenominator = tmpDenominator.divide(gcd); if (tmpDenominator.signum() < 0) { tmpNumerator = tmpNumerator.negate(); tmpDenominator = tmpDenominator.negate(); } return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES); }
public BigDecimal getBigDecimal(int scale) throws SQLException { truncated_ = 0; outOfBounds_ = false; if (scale >= 0) { if (scale >= value_.scale()) { truncated_ = 0; outOfBounds_ = false; return value_.setScale(scale); } else { truncated_ = value_.scale() - scale; return value_.setScale(scale, BigDecimal.ROUND_HALF_UP); } } else return value_; }
@Override public void write(WriteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { super.write(buff, obj); return; } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale); } buff.putVarLong(b.longValue()); } else { byte[] bytes = b.toByteArray(); buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes); } } }
@Override public void write(final ObjectDataOutput out, final BigDecimal obj) throws IOException { BigInteger bigInt = obj.unscaledValue(); int scale = obj.scale(); bigIntegerSerializer.write(out, bigInt); out.writeInt(scale); }
/** * @param minValue * @param maxValue * @param scale * @param isForFunctionalBin Functional bins should always be non-sci notation. * @return */ public static DecimalFormat getFormat( BigDecimal minValue, BigDecimal maxValue, int scale, boolean isForFunctionalBin) { // Find number of digits left of decimal BigDecimal maxAbs = minValue.abs(); maxAbs = maxAbs.max(maxValue.abs()); int digitsLeftOfDecimal = Math.abs(maxAbs.precision() - maxAbs.scale()); boolean useSciNotation = (digitsLeftOfDecimal > 4 || scale > 4) && !isForFunctionalBin; String formatStr = null; if (useSciNotation) { if (scale > 0) { // Sig figs beyond the decimal (decimal fraction number) formatStr = "0." + StringUtils.repeat("0", scale) + "E0"; } else { // will contain no decimal number formatStr = "##0.##E0"; } } else { if (scale > 0) { // Sig figs beyond the decimal (decimal fraction number) formatStr = "0." + StringUtils.repeat("0", scale); } else { // will contain no decimal number formatStr = "0"; } } return new DecimalFormat(formatStr); }
@Override public ByteBuffer write(ByteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { return super.write(buff, obj); } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED); DataUtils.writeVarInt(buff, scale); } DataUtils.writeVarLong(buff, b.longValue()); } else { buff.put((byte) TYPE_BIG_DECIMAL); DataUtils.writeVarInt(buff, scale); byte[] bytes = b.toByteArray(); DataUtils.writeVarInt(buff, bytes.length); buff = DataUtils.ensureCapacity(buff, bytes.length); buff.put(bytes); } } return buff; }
private static BigInteger getNearby(BigInteger significand, int binExp, int offset) { int nExtraBits = 1; int nDec = (int) Math.round(3.0 + (64 + nExtraBits) * Math.log10(2.0)); BigInteger newFrac = significand.shiftLeft(nExtraBits).add(BigInteger.valueOf(offset)); int gg = 64 + nExtraBits - binExp - 1; BigDecimal bd = new BigDecimal(newFrac); if (gg > 0) { bd = bd.divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg))); } else { BigInteger frac = newFrac; while (frac.bitLength() + binExp < 180) { frac = frac.multiply(BigInteger.TEN); } int binaryExp = binExp - newFrac.bitLength() + frac.bitLength(); bd = new BigDecimal(frac.shiftRight(frac.bitLength() - binaryExp - 1)); } int excessPrecision = bd.precision() - nDec; if (excessPrecision > 0) { bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP); } return bd.unscaledValue(); }
/** * The constructor does not complex computations and requires simple, inputs consistent with the * class invariant. Other creation methods are available for convenience. */ public Money(BigDecimal amount, Currency currency) { if (amount.scale() != currency.getDefaultFractionDigits()) { throw new IllegalArgumentException("Scale of amount does not match currency"); } this.currency = currency; this.amount = amount; }
private static short[] pgNumericVar(BigDecimal n) { short ndigits, weight, sign, dscale; dscale = (short) n.scale(); if (dscale < 0) dscale = 0; String s = n.toPlainString(); int lpos = 0; sign = NUMERIC_POS; if (s.charAt(lpos) == '-') { sign = NUMERIC_NEG; lpos++; } int dposl = s.indexOf('.', lpos), dposr; if (dposl < 0) dposr = dposl = s.length(); else dposr = dposl + 1; int nleft = (dposl - lpos + 3) / 4; weight = (short) (nleft - 1); int nright = (s.length() - dposr + 3) / 4; ndigits = (short) (nleft + nright); while ((ndigits > 0) && (pgNumericDigit(s, ndigits - 1, lpos, dposl, dposr, nleft, nright) == 0)) { ndigits--; } short[] digits = new short[ndigits + 4]; digits[0] = ndigits; digits[1] = weight; digits[2] = sign; digits[3] = dscale; for (int i = 0; i < ndigits; i++) { digits[i + 4] = pgNumericDigit(s, i, lpos, dposl, dposr, nleft, nright); } return digits; }
/** * Convert a BigDecimal value to a byte array * * @param val * @return the byte array */ public static byte[] toBytes(BigDecimal val) { byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; int offset = putInt(result, 0, val.scale()); putBytes(result, offset, valueBytes, 0, valueBytes.length); return result; }
public static DecBase toDec(BigDecimal bd) { boolean bPositive = true; if (bd.signum() < 0) bPositive = false; String sValue = bd.abs().unscaledValue().toString(); int nScale = bd.scale(); if (sValue.length() > nScale) { String sInt = sValue.substring(0, sValue.length() - nScale); String sDec = sValue.substring(sValue.length() - nScale); DecBase dec = new DecBase(sInt, sDec); dec.setPositive(bPositive); return dec; } else { String sDec = new String(); int nNbLeadingZeros = nScale - sValue.length(); for (int n = 0; n < nNbLeadingZeros; n++) { sDec = sDec + "0"; } sDec = sDec + sValue; DecBase dec = new DecBase(0, sDec); dec.setPositive(bPositive); return dec; } }
public static String castToString(BigDecimal val) { int sign = val.signum(); val = val.abs(); String s = val.unscaledValue().toString(); while (s.length() <= val.scale()) s = "0" + s; while (s.length() < -val.scale()) s = s + "0"; if (val.scale() > 0) { s = s.substring(0, s.length() - val.scale()) + "." + s.substring(s.length() - val.scale(), s.length()); while (s.endsWith("0")) s = s.substring(0, s.length() - 1); if (s.endsWith(".")) s = s.substring(0, s.length() - 1); } if (sign < 0) s = "-" + s; return s; }
@Override public int getDecimalScale() { BigDecimal d = getDecimal(); if (d != null) { return d.scale(); } return 0; }
public CalculatorToken(BigDecimal v, boolean approx) { this.value = v; this.isApprox = approx; if (approx) { this.minScale = v.scale(); this.minPrecision = v.precision(); } }
@Test public void testConvertToWalletAmount() { WalletAmountConverter wac = new WalletAmountConverter(2); BigDecimal a = wac.convertToWalletAmount(-12345); assertEquals(new BigDecimal("-123.45"), a); assertEquals(2, a.scale()); }
@Override public void comply(final E object) throws Exception { if (object == null) return; final int integerPartLength; final int fractionPartLength; try { final BigDecimal bigNum; if (object instanceof BigDecimal) bigNum = (BigDecimal) object; else bigNum = new BigDecimal(object.toString()).stripTrailingZeros(); integerPartLength = bigNum.precision() - bigNum.scale(); fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale(); } catch (Exception ex) { throw ex; } if (maxIntegerLength < integerPartLength || maxFractionLength < fractionPartLength) throw ex; }
@Override protected void writeObject(ObjectOutput out, Object obj) throws IOException { BigDecimal val = (BigDecimal) obj; out.writeInt(val.scale()); BigInteger unscaled = val.unscaledValue(); byte[] bytes = unscaled.toByteArray(); out.writeInt(bytes.length); out.write(bytes); }
public static double calcIncrement(double value) { BigDecimal b = BigDecimal.valueOf(value); BigDecimal r = b.remainder(BigDecimal.ONE); if (r.compareTo(BigDecimal.ZERO) == 0) { return 1; } double res = 1 / Math.pow(10, r.scale()); return res; }
public BigDecimal getBigDecimal(int scale) throws SQLException { truncated_ = 0; try { BigDecimal bigDecimal = new BigDecimal(SQLDataFactory.convertScientificNotation(value_)); if (scale >= 0) { if (scale >= bigDecimal.scale()) { truncated_ = 0; return bigDecimal.setScale(scale); } else { truncated_ = bigDecimal.scale() - scale; return bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP); } } else return bigDecimal; } catch (NumberFormatException e) { JDError.throwSQLException(this, JDError.EXC_DATA_TYPE_MISMATCH, e); return null; } }
protected BigDecimal roundCost(BigDecimal price, int C_AcctSchema_ID) { // Fix Cost Precision int precision = MAcctSchema.get(Env.getCtx(), C_AcctSchema_ID).getCostingPrecision(); BigDecimal priceRounded = price; if (priceRounded.scale() > precision) { priceRounded = priceRounded.setScale(precision, RoundingMode.HALF_UP); } return priceRounded; }
/** * Returns the scale (ie the BigDecimal concept of scale) of the most significant digit of the * value. * * <p>Examples: * * <ul> * <li>The scale of 1.49523 is 0 * <li>The scale of 0.149523 is 1 * <li>The scale of 14.9523 is -1 * <li>The scale of 0 is 0 * * @param value * @return */ public static int getScaleOfMostSignificantDigit(BigDecimal value) { if (value.compareTo(BigDecimal.ZERO) == 0) { // Some multi-decimal place forms of zero return a non-zero result // for the equation below, even when stripped. return 0; } else { return value.scale() - value.precision() + 1; } }
public static String getBaseDecimal(ExpandedDouble hd) { int gg = 64 - hd.getBinaryExponent() - 1; BigDecimal bd = new BigDecimal(hd.getSignificand()).divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg))); int excessPrecision = bd.precision() - 23; if (excessPrecision > 0) { bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP); } return bd.unscaledValue().toString(); }
public static SMTAffineTerm create(Rational factor, Term subterm) { Sort sort = subterm.getSort(); Map<Term, Rational> summands; Rational constant; if (factor.equals(Rational.ZERO)) { summands = Collections.emptyMap(); constant = Rational.ZERO; } else if (subterm instanceof SMTAffineTerm) { SMTAffineTerm a = (SMTAffineTerm) subterm; constant = a.mConstant.mul(factor); summands = new HashMap<Term, Rational>(); for (Map.Entry<Term, Rational> me : a.mSummands.entrySet()) { summands.put(me.getKey(), me.getValue().mul(factor)); } } else if (subterm instanceof ConstantTerm) { Object value = ((ConstantTerm) subterm).getValue(); if (value instanceof BigInteger) { constant = Rational.valueOf((BigInteger) value, BigInteger.ONE).mul(factor); summands = Collections.emptyMap(); } else if (value instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) value; if (decimal.scale() <= 0) { BigInteger num = decimal.toBigInteger(); constant = Rational.valueOf(num, BigInteger.ONE).mul(factor); } else { BigInteger num = decimal.unscaledValue(); BigInteger denom = BigInteger.TEN.pow(decimal.scale()); constant = Rational.valueOf(num, denom).mul(factor); } summands = Collections.emptyMap(); } else if (value instanceof Rational) { constant = (Rational) value; summands = Collections.emptyMap(); } else { summands = Collections.singletonMap(subterm, factor); constant = Rational.ZERO; } } else { summands = Collections.singletonMap(subterm, factor); constant = Rational.ZERO; } return create(summands, constant, sort); }
public final BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { BigDecimal dec = getBigDecimal(columnIndex); if (dec == null) { return null; } if (dec.scale() != scale) { return dec.setScale(scale, BigDecimal.ROUND_HALF_EVEN); } return dec; }
/** * Put a BigDecimal value out to the specified byte array position. * * @param bytes the byte array * @param offset position in the array * @param val BigDecimal to write out * @return incremented offset */ public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) { if (bytes == null) { return offset; } byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; offset = putInt(result, offset, val.scale()); return putBytes(result, offset, valueBytes, 0, valueBytes.length); }