Example usage for java.math BigDecimal unscaledValue

List of usage examples for java.math BigDecimal unscaledValue

Introduction

In this page you can find the example usage for java.math BigDecimal unscaledValue.

Prototype

public BigInteger unscaledValue() 

Source Link

Document

Returns a BigInteger whose value is the unscaled value of this BigDecimal .

Usage

From source file:org.apache.arrow.vector.ipc.JsonFileWriter.java

private void writeValueToGenerator(BufferType bufferType, ArrowBuf buffer, ArrowBuf offsetBuffer,
        FieldVector vector, final int index, final int scale) throws IOException {
    if (bufferType.equals(TYPE)) {
        generator.writeNumber(buffer.getByte(index * TinyIntVector.TYPE_WIDTH));
    } else if (bufferType.equals(OFFSET)) {
        generator.writeNumber(buffer.getInt(index * BaseVariableWidthVector.OFFSET_WIDTH));
    } else if (bufferType.equals(VALIDITY)) {
        generator.writeNumber(vector.isNull(index) ? 0 : 1);
    } else if (bufferType.equals(DATA)) {
        switch (vector.getMinorType()) {
        case TINYINT:
            generator.writeNumber(TinyIntVector.get(buffer, index));
            break;
        case SMALLINT:
            generator.writeNumber(SmallIntVector.get(buffer, index));
            break;
        case INT:
            generator.writeNumber(IntVector.get(buffer, index));
            break;
        case BIGINT:
            generator.writeNumber(BigIntVector.get(buffer, index));
            break;
        case FLOAT4:
            generator.writeNumber(Float4Vector.get(buffer, index));
            break;
        case FLOAT8:
            generator.writeNumber(Float8Vector.get(buffer, index));
            break;
        case DATEDAY:
            generator.writeNumber(DateDayVector.get(buffer, index));
            break;
        case DATEMILLI:
            generator.writeNumber(DateMilliVector.get(buffer, index));
            break;
        case TIMESEC:
            generator.writeNumber(TimeSecVector.get(buffer, index));
            break;
        case TIMEMILLI:
            generator.writeNumber(TimeMilliVector.get(buffer, index));
            break;
        case TIMEMICRO:
            generator.writeNumber(TimeMicroVector.get(buffer, index));
            break;
        case TIMENANO:
            generator.writeNumber(TimeNanoVector.get(buffer, index));
            break;
        case TIMESTAMPSEC:
            generator.writeNumber(TimeStampSecVector.get(buffer, index));
            break;
        case TIMESTAMPMILLI:
            generator.writeNumber(TimeStampMilliVector.get(buffer, index));
            break;
        case TIMESTAMPMICRO:
            generator.writeNumber(TimeStampMicroVector.get(buffer, index));
            break;
        case TIMESTAMPNANO:
            generator.writeNumber(TimeStampNanoVector.get(buffer, index));
            break;
        case TIMESTAMPSECTZ:
            generator.writeNumber(TimeStampSecTZVector.get(buffer, index));
            break;
        case TIMESTAMPMILLITZ:
            generator.writeNumber(TimeStampMilliTZVector.get(buffer, index));
            break;
        case TIMESTAMPMICROTZ:
            generator.writeNumber(TimeStampMicroTZVector.get(buffer, index));
            break;
        case TIMESTAMPNANOTZ:
            generator.writeNumber(TimeStampNanoTZVector.get(buffer, index));
            break;
        case BIT:
            generator.writeNumber(BitVectorHelper.get(buffer, index));
            break;
        case VARBINARY: {
            assert offsetBuffer != null;
            String hexString = Hex.encodeHexString(BaseVariableWidthVector.get(buffer, offsetBuffer, index));
            generator.writeObject(hexString);
            break;
        }//from w  ww.  j  av  a  2s. c o  m
        case VARCHAR: {
            assert offsetBuffer != null;
            byte[] b = (BaseVariableWidthVector.get(buffer, offsetBuffer, index));
            generator.writeString(new String(b, "UTF-8"));
            break;
        }
        case DECIMAL: {
            BigDecimal decimalValue = DecimalUtility.getBigDecimalFromArrowBuf(buffer, index, scale);
            // We write the unscaled value, because the scale is stored in the type metadata.
            generator.writeString(decimalValue.unscaledValue().toString());
            break;
        }
        default:
            throw new UnsupportedOperationException("minor type: " + vector.getMinorType());
        }
    }
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Convert a BigDecimal value to a byte array
 *
 * @param val// ww  w  . ja  v  a2  s.co  m
 * @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;
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.RexNodeConverter.java

protected RexNode convert(ExprNodeConstantDesc literal) throws CalciteSemanticException {
    RexBuilder rexBuilder = cluster.getRexBuilder();
    RelDataTypeFactory dtFactory = rexBuilder.getTypeFactory();
    PrimitiveTypeInfo hiveType = (PrimitiveTypeInfo) literal.getTypeInfo();
    RelDataType calciteDataType = TypeConverter.convert(hiveType, dtFactory);

    PrimitiveCategory hiveTypeCategory = hiveType.getPrimitiveCategory();

    ConstantObjectInspector coi = literal.getWritableObjectInspector();
    Object value = ObjectInspectorUtils.copyToStandardJavaObject(coi.getWritableConstantValue(), coi);

    RexNode calciteLiteral = null;// ww  w .ja va 2s  . com
    // TODO: Verify if we need to use ConstantObjectInspector to unwrap data
    switch (hiveTypeCategory) {
    case BOOLEAN:
        calciteLiteral = rexBuilder.makeLiteral(((Boolean) value).booleanValue());
        break;
    case BYTE:
        calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Byte) value), calciteDataType);
        break;
    case SHORT:
        calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Short) value), calciteDataType);
        break;
    case INT:
        calciteLiteral = rexBuilder.makeExactLiteral(new BigDecimal((Integer) value));
        break;
    case LONG:
        calciteLiteral = rexBuilder.makeBigintLiteral(new BigDecimal((Long) value));
        break;
    // TODO: is Decimal an exact numeric or approximate numeric?
    case DECIMAL:
        if (value instanceof HiveDecimal) {
            value = ((HiveDecimal) value).bigDecimalValue();
        } else if (value instanceof Decimal128) {
            value = ((Decimal128) value).toBigDecimal();
        }
        if (value == null) {
            // We have found an invalid decimal value while enforcing precision and
            // scale. Ideally,
            // we would replace it with null here, which is what Hive does. However,
            // we need to plumb
            // this thru up somehow, because otherwise having different expression
            // type in AST causes
            // the plan generation to fail after CBO, probably due to some residual
            // state in SA/QB.
            // For now, we will not run CBO in the presence of invalid decimal
            // literals.
            throw new CalciteSemanticException(
                    "Expression " + literal.getExprString() + " is not a valid decimal",
                    UnsupportedFeature.Invalid_decimal);
            // TODO: return createNullLiteral(literal);
        }
        BigDecimal bd = (BigDecimal) value;
        BigInteger unscaled = bd.unscaledValue();
        if (unscaled.compareTo(MIN_LONG_BI) >= 0 && unscaled.compareTo(MAX_LONG_BI) <= 0) {
            calciteLiteral = rexBuilder.makeExactLiteral(bd);
        } else {
            // CBO doesn't support unlimited precision decimals. In practice, this
            // will work...
            // An alternative would be to throw CboSemanticException and fall back
            // to no CBO.
            RelDataType relType = cluster.getTypeFactory().createSqlType(SqlTypeName.DECIMAL, bd.scale(),
                    unscaled.toString().length());
            calciteLiteral = rexBuilder.makeExactLiteral(bd, relType);
        }
        break;
    case FLOAT:
        calciteLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Float) value), calciteDataType);
        break;
    case DOUBLE:
        calciteLiteral = rexBuilder.makeApproxLiteral(new BigDecimal((Double) value), calciteDataType);
        break;
    case CHAR:
        if (value instanceof HiveChar) {
            value = ((HiveChar) value).getValue();
        }
        calciteLiteral = rexBuilder.makeLiteral((String) value);
        break;
    case VARCHAR:
        if (value instanceof HiveVarchar) {
            value = ((HiveVarchar) value).getValue();
        }
        calciteLiteral = rexBuilder.makeLiteral((String) value);
        break;
    case STRING:
        calciteLiteral = rexBuilder.makeLiteral((String) value);
        break;
    case DATE:
        Calendar cal = new GregorianCalendar();
        cal.setTime((Date) value);
        calciteLiteral = rexBuilder.makeDateLiteral(cal);
        break;
    case TIMESTAMP:
        Calendar c = null;
        if (value instanceof Calendar) {
            c = (Calendar) value;
        } else {
            c = Calendar.getInstance();
            c.setTimeInMillis(((Timestamp) value).getTime());
        }
        calciteLiteral = rexBuilder.makeTimestampLiteral(c, RelDataType.PRECISION_NOT_SPECIFIED);
        break;
    case INTERVAL_YEAR_MONTH:
        // Calcite year-month literal value is months as BigDecimal
        BigDecimal totalMonths = BigDecimal.valueOf(((HiveIntervalYearMonth) value).getTotalMonths());
        calciteLiteral = rexBuilder.makeIntervalLiteral(totalMonths,
                new SqlIntervalQualifier(TimeUnit.YEAR, TimeUnit.MONTH, new SqlParserPos(1, 1)));
        break;
    case INTERVAL_DAY_TIME:
        // Calcite day-time interval is millis value as BigDecimal
        // Seconds converted to millis
        BigDecimal secsValueBd = BigDecimal.valueOf(((HiveIntervalDayTime) value).getTotalSeconds() * 1000);
        // Nanos converted to millis
        BigDecimal nanosValueBd = BigDecimal.valueOf(((HiveIntervalDayTime) value).getNanos(), 6);
        calciteLiteral = rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd),
                new SqlIntervalQualifier(TimeUnit.DAY, TimeUnit.SECOND, new SqlParserPos(1, 1)));
        break;
    case VOID:
        calciteLiteral = cluster.getRexBuilder().makeLiteral(null,
                cluster.getTypeFactory().createSqlType(SqlTypeName.NULL), true);
        break;
    case BINARY:
    case UNKNOWN:
    default:
        throw new RuntimeException("UnSupported Literal");
    }

    return calciteLiteral;
}

From source file:org.apache.hadoop.hive.ql.exec.ColumnStatsUpdateTask.java

private ColumnStatistics constructColumnStatsFromInput() throws SemanticException, MetaException {

    String dbName = SessionState.get().getCurrentDatabase();
    ColumnStatsDesc desc = work.getColStats();
    String tableName = desc.getTableName();
    String partName = work.getPartName();
    List<String> colName = desc.getColName();
    List<String> colType = desc.getColType();

    ColumnStatisticsObj statsObj = new ColumnStatisticsObj();

    // grammar prohibits more than 1 column so we are guaranteed to have only 1
    // element in this lists.

    statsObj.setColName(colName.get(0));

    statsObj.setColType(colType.get(0));

    ColumnStatisticsData statsData = new ColumnStatisticsData();

    String columnType = colType.get(0);

    if (columnType.equalsIgnoreCase("long")) {
        LongColumnStatsData longStats = new LongColumnStatsData();
        longStats.setNumNullsIsSet(false);
        longStats.setNumDVsIsSet(false);
        longStats.setLowValueIsSet(false);
        longStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                longStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                longStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                longStats.setLowValue(Long.parseLong(value));
            } else if (fName.equals("highValue")) {
                longStats.setHighValue(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }/*from  ww w .j a v  a  2s. c om*/

        }
        statsData.setLongStats(longStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("double")) {
        DoubleColumnStatsData doubleStats = new DoubleColumnStatsData();
        doubleStats.setNumNullsIsSet(false);
        doubleStats.setNumDVsIsSet(false);
        doubleStats.setLowValueIsSet(false);
        doubleStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                doubleStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                doubleStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                doubleStats.setLowValue(Double.parseDouble(value));
            } else if (fName.equals("highValue")) {
                doubleStats.setHighValue(Double.parseDouble(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDoubleStats(doubleStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("string")) {
        StringColumnStatsData stringStats = new StringColumnStatsData();
        stringStats.setMaxColLenIsSet(false);
        stringStats.setAvgColLenIsSet(false);
        stringStats.setNumNullsIsSet(false);
        stringStats.setNumDVsIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                stringStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                stringStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("avgColLen")) {
                stringStats.setAvgColLen(Double.parseDouble(value));
            } else if (fName.equals("maxColLen")) {
                stringStats.setMaxColLen(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setStringStats(stringStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("boolean")) {
        BooleanColumnStatsData booleanStats = new BooleanColumnStatsData();
        booleanStats.setNumNullsIsSet(false);
        booleanStats.setNumTruesIsSet(false);
        booleanStats.setNumFalsesIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                booleanStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numTrues")) {
                booleanStats.setNumTrues(Long.parseLong(value));
            } else if (fName.equals("numFalses")) {
                booleanStats.setNumFalses(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setBooleanStats(booleanStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("binary")) {
        BinaryColumnStatsData binaryStats = new BinaryColumnStatsData();
        binaryStats.setNumNullsIsSet(false);
        binaryStats.setAvgColLenIsSet(false);
        binaryStats.setMaxColLenIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                binaryStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("avgColLen")) {
                binaryStats.setAvgColLen(Double.parseDouble(value));
            } else if (fName.equals("maxColLen")) {
                binaryStats.setMaxColLen(Long.parseLong(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setBinaryStats(binaryStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("decimal")) {
        DecimalColumnStatsData decimalStats = new DecimalColumnStatsData();
        decimalStats.setNumNullsIsSet(false);
        decimalStats.setNumDVsIsSet(false);
        decimalStats.setLowValueIsSet(false);
        decimalStats.setHighValueIsSet(false);
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                decimalStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                decimalStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                BigDecimal d = new BigDecimal(value);
                decimalStats.setLowValue(
                        new Decimal(ByteBuffer.wrap(d.unscaledValue().toByteArray()), (short) d.scale()));
            } else if (fName.equals("highValue")) {
                BigDecimal d = new BigDecimal(value);
                decimalStats.setHighValue(
                        new Decimal(ByteBuffer.wrap(d.unscaledValue().toByteArray()), (short) d.scale()));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDecimalStats(decimalStats);
        statsObj.setStatsData(statsData);
    } else if (columnType.equalsIgnoreCase("date")) {
        DateColumnStatsData dateStats = new DateColumnStatsData();
        Map<String, String> mapProp = work.getMapProp();
        for (Entry<String, String> entry : mapProp.entrySet()) {
            String fName = entry.getKey();
            String value = entry.getValue();
            if (fName.equals("numNulls")) {
                dateStats.setNumNulls(Long.parseLong(value));
            } else if (fName.equals("numDVs")) {
                dateStats.setNumDVs(Long.parseLong(value));
            } else if (fName.equals("lowValue")) {
                // Date high/low value is stored as long in stats DB, but allow users to set high/low
                // value using either date format (yyyy-mm-dd) or numeric format (days since epoch)
                dateStats.setLowValue(readDateValue(value));
            } else if (fName.equals("highValue")) {
                dateStats.setHighValue(readDateValue(value));
            } else {
                throw new SemanticException("Unknown stat");
            }
        }
        statsData.setDateStats(dateStats);
        statsObj.setStatsData(statsData);
    } else {
        throw new SemanticException("Unsupported type");
    }
    String[] names = Utilities.getDbTableName(dbName, tableName);
    ColumnStatisticsDesc statsDesc = getColumnStatsDesc(names[0], names[1], partName, partName == null);
    ColumnStatistics colStat = new ColumnStatistics();
    colStat.setStatsDesc(statsDesc);
    colStat.addToStatsObj(statsObj);
    return colStat;
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Put a BigDecimal value out to the specified byte array position.
 *
 * @param bytes  the byte array/* www.  j a v  a 2 s  .c  o  m*/
 * @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);
}

From source file:org.ojai.json.impl.JsonStreamDocumentReader.java

@Override
public ByteBuffer getDecimalValueAsBytes() {
    BigDecimal decimal = getDecimal();
    if (decimal != null) {
        BigInteger decimalInteger = decimal.unscaledValue();
        byte[] bytearray = decimalInteger.toByteArray();
        return ByteBuffer.wrap(bytearray);
    }/*from  w w  w  .j  a  v a2  s  .  c o m*/
    return null;
}

From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java

static byte[] toUnscaledByteArray(BigDecimal decVal, int maxByteLen) throws IOException {
    // convert to unscaled BigInteger, big-endian bytes
    byte[] intValBytes = decVal.unscaledValue().toByteArray();
    if (intValBytes.length > maxByteLen) {
        if ((intValBytes[0] == 0) && ((intValBytes.length - 1) == maxByteLen)) {
            // in order to not return a negative two's complement value,
            // toByteArray() may return an extra leading 0 byte.  we are working
            // with unsigned values, so we can drop the extra leading 0
            intValBytes = ByteUtil.copyOf(intValBytes, 1, maxByteLen);
        } else {/*  www  .  j a v a2s  .co  m*/
            throw new IOException("Too many bytes for valid BigInteger?");
        }
    } else if (intValBytes.length < maxByteLen) {
        intValBytes = ByteUtil.copyOf(intValBytes, 0, maxByteLen, (maxByteLen - intValBytes.length));
    }
    return intValBytes;
}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance that represents the value of {@code value}.
 *
 * @param value the value.//ww w  .ja  v  a2 s. co m
 * @return An instance that represents the value of {@code value}.
 */
@Nullable
public static Rational valueOf(@Nullable BigDecimal value) {
    if (value == null) {
        return null;
    }
    BigInteger numerator;
    BigInteger denominator;
    if (value.signum() == 0) {
        return ZERO;
    }
    if (BigDecimal.ONE.equals(value)) {
        return ONE;
    }
    if (value.scale() > 0) {
        BigInteger unscaled = value.unscaledValue();
        BigInteger tmpDenominator = BigInteger.TEN.pow(value.scale());
        BigInteger tmpGreatestCommonDivisor = unscaled.gcd(tmpDenominator);
        numerator = unscaled.divide(tmpGreatestCommonDivisor);
        denominator = tmpDenominator.divide(tmpGreatestCommonDivisor);
    } else {
        numerator = value.toBigIntegerExact();
        denominator = BigInteger.ONE;
    }
    return new Rational(numerator, denominator, BigInteger.ONE, numerator, denominator);
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes a numeric value./*from ww  w  .  jav a2s .c  o m*/
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0);
        if (negative) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put(negative ? (byte) 0x80 : (byte) 0);

        // adjust scale according to this column type (will cause the an
        // ArithmeticException if number has too many decimal places)
        decVal = decVal.setScale(getScale());

        // check precision
        if (decVal.precision() > getPrecision()) {
            throw new IOException(
                    "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal);
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = decVal.unscaledValue().toByteArray();
        int maxByteLen = getType().getFixedSize() - 1;
        if (intValBytes.length > maxByteLen) {
            throw new IOException("Too many bytes for valid BigInteger?");
        }
        if (intValBytes.length < maxByteLen) {
            byte[] tmpBytes = new byte[maxByteLen];
            System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length);
            intValBytes = tmpBytes;
        }
        if (buffer.order() != ByteOrder.BIG_ENDIAN) {
            fixNumericByteOrder(intValBytes);
        }
        buffer.put(intValBytes);
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e);
    }
}