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

The following examples show how to use java.math.BigDecimal#unscaledValue() . 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: TestKeyBuilder.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dumps out interesting bits of the {@link BigDecimal} state.
 * 
 * @return The dump.
 */
private String dumpBigDecimal(final BigDecimal i) {

  final BigInteger unscaled = i.unscaledValue();

  final String msg = i.toString() + ", scale=" + i.scale()
          + //
          ", precision=" + i.precision()
          + //
          ", unscaled=" + unscaled
          + //
          ", unscaled_byte[]="
          + BytesUtil.toString(unscaled.toByteArray())//
  ;

    return msg;

}
 
Example 2
Source File: LmdbDataOutput.java    From hypergraphdb with Apache License 2.0 6 votes vote down vote up
/**
 * Writes an unsorted {@code BigDecimal}.
 * 
 * @throws NullPointerException
 *           if val is null.
 * 
 * @see <a href="package-summary.html#bigDecimalFormats">BigDecimal Formats</a>
 */
public final HGDataOutput writeBigDecimal(BigDecimal val) {
	/*
	 * The byte format for a BigDecimal value is: Byte 0 ~ L: The scale part written as a PackedInteger. Byte
	 * L+1 ~ M: The length of the unscaled value written as a PackedInteger. Byte M+1 ~ N: The
	 * BigDecimal.toByteArray array, written without modification.
	 * 
	 * Get the scale and the unscaled value of this BigDecimal.
	 */
	int scale = val.scale();
	BigInteger unscaledVal = val.unscaledValue();

	/* Store the scale. */
	writePackedInt(scale);
	byte[] a = unscaledVal.toByteArray();
	int len = a.length;

	/* Store the length of the following bytes. */
	writePackedInt(len);

	/* Store the bytes of the BigDecimal, without modification. */
	writeFast(a, 0, len);
	return this;
}
 
Example 3
Source File: DurationImpl.java    From openjdk-8 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 4
Source File: RequestStream.java    From jTDS with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Write a BigDecimal value to the output stream.
 *
 * @param value The BigDecimal value to write.
 * @throws IOException
 */
void write(BigDecimal value) throws IOException {

    if (value == null) {
        write((byte) 0);
    } else {
        byte signum = (byte) (value.signum() < 0 ? 0 : 1);
        BigInteger bi = value.unscaledValue();
        byte mantisse[] = bi.abs().toByteArray();
        byte len = (byte) (mantisse.length + 1);

        if (len > getMaxDecimalBytes()) {
            // Should never happen now as value is normalized elsewhere
            throw new IOException("BigDecimal to big to send");
        }

        if (socket.serverType == Driver.SYBASE) {
            write(len);
            // Sybase TDS5 stores MSB first opposite sign!
            // length, prec, scale already sent in parameter descriptor.
            write((byte) ((signum == 0) ? 1 : 0));

            for (int i = 0; i < mantisse.length; i++) {
                write(mantisse[i]);
            }
        } else {
            write(len);
            write(signum);

            for (int i = mantisse.length - 1; i >= 0; i--) {
                write(mantisse[i]);
            }
        }
    }
}
 
Example 5
Source File: RowOutputBinary.java    From evosql with Apache License 2.0 5 votes vote down vote up
protected void writeDecimal(BigDecimal o, Type type) {

        int        scale   = o.scale();
        BigInteger bigint  = o.unscaledValue();
        byte[]     bytearr = bigint.toByteArray();

        writeByteArray(bytearr);
        writeInt(scale);
    }
 
Example 6
Source File: DurationImpl.java    From openjdk-jdk8u-backup 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 7
Source File: BigDecimalSerializer.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void write(WriteBuffer buffer, BigDecimal attribute) {
    BigInteger unscaledVal = attribute.unscaledValue();
    int scale = attribute.scale();
    bigIntegerDelegate.write(buffer, unscaledVal);
    buffer.putInt(scale);
}
 
Example 8
Source File: CqlMapper.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Override
ByteBuffer encodeInternal(BigDecimal input) {
  BigInteger bi = input.unscaledValue();
  int scale = input.scale();
  byte[] bibytes = bi.toByteArray();

  ByteBuffer bytes = ByteBuffer.allocate(4 + bibytes.length);
  bytes.putInt(scale);
  bytes.put(bibytes);
  bytes.rewind();
  return bytes;
}
 
Example 9
Source File: BinaryWriterExImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param val String value.
 */
public void doWriteDecimal(@Nullable BigDecimal val) {
    if (val == null)
        out.writeByte(GridBinaryMarshaller.NULL);
    else {
        out.unsafeEnsure(1 + 4 + 4);

        out.unsafeWriteByte(GridBinaryMarshaller.DECIMAL);

        out.unsafeWriteInt(val.scale());

        BigInteger intVal = val.unscaledValue();

        boolean negative = intVal.signum() == -1;

        if (negative)
            intVal = intVal.negate();

        byte[] vals = intVal.toByteArray();

        if (negative)
            vals[0] |= -0x80;

        out.unsafeWriteInt(vals.length);
        out.writeByteArray(vals);
    }
}
 
Example 10
Source File: DurationImpl.java    From jdk1.8-source-analysis with Apache License 2.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 11
Source File: BigDecimalSerializer.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void write(WriteBuffer buffer, BigDecimal attribute) {
    BigInteger unscaledVal = attribute.unscaledValue();
    int scale = attribute.scale();
    bigIntegerDelegate.write(buffer, unscaledVal);
    buffer.putInt(scale);
}
 
Example 12
Source File: BigDecimalOperators.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static Number rationalize(BigDecimal number) {
    BigInteger unscaled = number.unscaledValue();
    int scale = number.scale();
    if (scale < 0) {
        return unscaled.multiply(BigInteger.TEN.pow(-scale));
    }
    return unscaled.divide(BigInteger.TEN.pow(scale));
}
 
Example 13
Source File: TestExpressionCompiler.java    From presto with Apache License 2.0 5 votes vote down vote up
private void assertExecute(List<String> expressions, BigDecimal decimal)
{
    Type type = getDecimalType(decimal);
    SqlDecimal value = decimal == null ? null : new SqlDecimal(decimal.unscaledValue(), decimal.precision(), decimal.scale());
    for (String expression : expressions) {
        assertExecute(expression, type, value);
    }
}
 
Example 14
Source File: AbstractTestDecimalAverageAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected SqlDecimal getExpectedValue(int start, int length)
{
    if (length == 0) {
        return null;
    }
    BigDecimal avg = BigDecimal.ZERO;
    for (int i = start; i < start + length; i++) {
        avg = avg.add(getBigDecimalForCounter(i));
    }
    avg = avg.divide(BigDecimal.valueOf(length), ROUND_HALF_UP);
    return new SqlDecimal(avg.unscaledValue(), avg.precision(), avg.scale());
}
 
Example 15
Source File: Decimal.java    From ion-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a "plain" {@link BigDecimal} instance, never a {@link Decimal}
 * subclass.  As a side effect, this strips any negative-zero information.
 *
 * @param val may be null.
 * @return {@code null} if the given value is {@code null}.
 */
public static BigDecimal bigDecimalValue(BigDecimal val)
{
    if (val == null
        || val.getClass() == BigDecimal.class)
    {
        return val;
    }
    return new BigDecimal(val.unscaledValue(), val.scale());
}
 
Example 16
Source File: Quantity.java    From moserp with Apache License 2.0 4 votes vote down vote up
public Quantity(BigDecimal bigDecimal) {
    value = new BigDecimal(bigDecimal.unscaledValue(), bigDecimal.scale(), new MathContext(bigDecimal.precision()));
}
 
Example 17
Source File: SimpleByteBuffer.java    From ion-java with Apache License 2.0 4 votes vote down vote up
private int writeDecimal(BigDecimal value, UserByteWriter userWriter) throws IOException
{
    int returnlen = 0;
    // we only write out the '0' value as the nibble 0
    if (value != null && !BigDecimal.ZERO.equals(value)) {
        // otherwise we do it the hard way ....
        BigInteger mantissa = value.unscaledValue();

        boolean isNegative = (mantissa.compareTo(BigInteger.ZERO) < 0);
        if (isNegative) {
            mantissa = mantissa.negate();
        }

        byte[] bits  = mantissa.toByteArray();
        int    scale = value.scale();

        // Ion stores exponent, BigDecimal uses the negation "scale"
        int exponent = -scale;
        if (userWriter != null) {
            returnlen += userWriter.writeIonInt(exponent, IonBinary.lenVarUInt(exponent));
        }
        else {
            returnlen += this.writeIonInt(exponent, IonBinary.lenVarUInt(exponent));
        }

        // If the first bit is set, we can't use it for the sign,
        // and we need to write an extra byte to hold it.
        boolean needExtraByteForSign = ((bits[0] & 0x80) != 0);
        if (needExtraByteForSign)
        {
            if (userWriter != null) {
                userWriter.write((byte)(isNegative ? 0x80 : 0x00));
            }
            else {
                this.write((byte)(isNegative ? 0x80 : 0x00));
            }
            returnlen++;
        }
        else if (isNegative)
        {
            bits[0] |= 0x80;
        }
        // if we have a userWriter to write to, we really don't care about
        // the value in our local buffer.
        if (userWriter != null) {
            userWriter.write(bits, 0, bits.length);
        }
        else {
            this.write(bits, 0, bits.length);
        }
        returnlen += bits.length;
    }
    return returnlen;
}
 
Example 18
Source File: IonRawBinaryWriter.java    From ion-java with Apache License 2.0 4 votes vote down vote up
public void writeTimestamp(final Timestamp value) throws IOException
{
    if (value == null)
    {
        writeNull(IonType.TIMESTAMP);
        return;
    }
    prepareValue();

    // optimistically try to fit a timestamp length in low nibble (most should)
    updateLength(1);
    pushContainer(ContainerType.VALUE);
    buffer.writeByte(TIMESTAMP_TYPE);

    // OFFSET
    final Integer offset = value.getLocalOffset();
    if (offset == null)
    {
        // special case for unknown -00:00
        updateLength(1);
        buffer.writeByte(VARINT_NEG_ZERO);
    }
    else
    {
        writeVarInt(offset.intValue());
    }

    // YEAR
    final int year = value.getZYear();
    writeVarUInt(year);

    // XXX it is really convenient to rely on the ordinal
    final int precision = value.getPrecision().ordinal();

    if (precision >= MONTH.ordinal())
    {
        final int month = value.getZMonth();
        writeVarUInt(month);
    }
    if (precision >= DAY.ordinal())
    {
        final int day = value.getZDay();
        writeVarUInt(day);
    }
    if (precision >= MINUTE.ordinal())
    {
        final int hour = value.getZHour();
        writeVarUInt(hour);
        final int minute = value.getZMinute();
        writeVarUInt(minute);
    }
    if (precision >= SECOND.ordinal())
    {
        final int second = value.getZSecond();
        writeVarUInt(second);
        final BigDecimal fraction = value.getZFractionalSecond();
        if (fraction != null) {
            final BigInteger mantissaBigInt = fraction.unscaledValue();
            final int exponent = -fraction.scale();
            if (!(mantissaBigInt.equals(BigInteger.ZERO) && exponent > -1)) {
                writeDecimalValue(fraction);
            }
        }
    }

    final ContainerInfo info = popContainer();
    patchSingleByteTypedOptimisticValue(TIMESTAMP_TYPE, info);

    finishValue();
}
 
Example 19
Source File: NumberUtil.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * @return whether a BigDecimal is a valid Farrago decimal. If a
 * BigDecimal's unscaled value overflows a long, then it is not a valid
 * Farrago decimal.
 */
public static boolean isValidDecimal(BigDecimal bd) {
  BigInteger usv = bd.unscaledValue();
  long usvl = usv.longValue();
  return usv.equals(BigInteger.valueOf(usvl));
}
 
Example 20
Source File: _Private_IonTextAppender.java    From ion-java with Apache License 2.0 4 votes vote down vote up
public void printDecimal(_Private_IonTextWriterBuilder _options,
                         BigDecimal                    value)
    throws IOException
{
    if (value == null)
    {
        appendAscii("null.decimal");
        return;
    }

    BigInteger unscaled = value.unscaledValue();

    int signum = value.signum();
    if (signum < 0)
    {
        appendAscii('-');
        unscaled = unscaled.negate();
    }
    else if (value instanceof Decimal
         && ((Decimal)value).isNegativeZero())
    {
        // for the various forms of negative zero we have to
        // write the sign ourselves, since neither BigInteger
        // nor BigDecimal recognize negative zero, but Ion does.
        appendAscii('-');
    }

    final String unscaledText = unscaled.toString();
    final int significantDigits = unscaledText.length();

    final int scale = value.scale();
    final int exponent = -scale;

    if (_options._decimal_as_float)
    {
        appendAscii(unscaledText);
        appendAscii('e');
        appendAscii(Integer.toString(exponent));
    }
    else if (exponent == 0)
    {
        appendAscii(unscaledText);
        appendAscii('.');
    }
    else if (exponent < 0)
    {
        // Avoid printing small negative exponents using a heuristic
        // adapted from http://speleotrove.com/decimal/daconvs.html

        final int adjustedExponent = significantDigits - 1 - scale;
        if (adjustedExponent >= 0)
        {
            int wholeDigits = significantDigits - scale;
            appendAscii(unscaledText, 0, wholeDigits);
            appendAscii('.');
            appendAscii(unscaledText, wholeDigits,
                                significantDigits);
        }
        else if (adjustedExponent >= -6)
        {
            appendAscii("0.");
            appendAscii("00000", 0, scale - significantDigits);
            appendAscii(unscaledText);
        }
        else
        {
            appendAscii(unscaledText);
            appendAscii("d-");
            appendAscii(Integer.toString(scale));
        }
    }
    else // (exponent > 0)
    {
        // We cannot move the decimal point to the right, adding
        // rightmost zeros, because that would alter the precision.
        appendAscii(unscaledText);
        appendAscii('d');
        appendAscii(Integer.toString(exponent));
    }
}