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

The following examples show how to use java.math.BigDecimal#longValue() . These examples are extracted from open source projects. 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 Project: QLExpress   File: OperatorOfNumber.java    License: Apache License 2.0 6 votes vote down vote up
public static Number subtractPrecise(Number op1, Number op2) throws Exception {
	BigDecimal result =  null;
	if(op1 instanceof BigDecimal){
		if(op2 instanceof BigDecimal){
			result = ((BigDecimal)op1).subtract((BigDecimal)op2);
		}else{
			result = ((BigDecimal)op1).subtract(new BigDecimal(op2.toString()));
		}
	}else{
		if(op2 instanceof BigDecimal){
			result = new BigDecimal(op1.toString()).subtract((BigDecimal)op2);
		}else{
			result = new BigDecimal(op1.toString()).subtract(new BigDecimal(op2.toString()));
		}
	}
	if(result.scale() ==0){
		long tempLong =  result.longValue();
		if(tempLong <= Integer.MAX_VALUE && tempLong >= Integer.MIN_VALUE){
			return (int)tempLong;
		}else{
			return tempLong;
		}
	}else{
		return result;
	}
}
 
Example 2
Source Project: phoenix   File: PTimestamp.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object toObject(Object object, PDataType actualType) {
    if (object == null) {
        return null;
    }
    if (equalsAny(actualType, PDate.INSTANCE, PUnsignedDate.INSTANCE, PTime.INSTANCE,
            PUnsignedTime.INSTANCE)) {
        return new java.sql.Timestamp(((java.util.Date) object).getTime());
    } else if (equalsAny(actualType, PTimestamp.INSTANCE, PUnsignedTimestamp.INSTANCE)) {
        return object;
    } else if (equalsAny(actualType, PLong.INSTANCE, PUnsignedLong.INSTANCE)) {
        return new java.sql.Timestamp((Long) object);
    } else if (actualType == PDecimal.INSTANCE) {
        BigDecimal bd = (BigDecimal) object;
        long ms = bd.longValue();
        int nanos =
                (bd.remainder(BigDecimal.ONE).multiply(QueryConstants.BD_MILLIS_NANOS_CONVERSION))
                .intValue();
        return DateUtil.getTimestamp(ms, nanos);
    } else if (actualType == PVarchar.INSTANCE) {
        return DateUtil.parseTimestamp((String) object);
    }
    return throwConstraintViolationException(actualType, this);
}
 
Example 3
/**
 * Test FloorMod of long arguments against expected value.
 * The expected value is usually a Long but in some cases  is
 * an ArithmeticException.
 *
 * @param x dividend
 * @param y modulus
 * @param expected expected value
 */
static void testLongFloorMod(long x, long y, Object expected) {
    Object result = doFloorMod(x, y);
    if (!resultEquals(result, expected)) {
        fail("FAIL: long Math.floorMod(%d, %d) = %s; expected %s%n", x, y, result, expected);
    }

    Object strict_result = doStrictFloorMod(x, y);
    if (!resultEquals(strict_result, expected)) {
        fail("FAIL: long StrictMath.floorMod(%d, %d) = %s; expected %s%n", x, y, strict_result, expected);
    }

    try {
        // Verify the result against BigDecimal rounding mode.
        BigDecimal xD = new BigDecimal(x);
        BigDecimal yD = new BigDecimal(y);
        BigDecimal resultD = xD.divide(yD, RoundingMode.FLOOR);
        resultD = resultD.multiply(yD);
        resultD = xD.subtract(resultD);
        long fr = resultD.longValue();
        if (!result.equals(fr)) {
            fail("FAIL: Long.floorMod(%d, %d) = %d is different than BigDecimal result: %d%n", x, y, result, fr);

        }
    } catch (ArithmeticException ae) {
        if (y != 0) {
            fail("FAIL: long Math.floorMod(%d, %d); unexpected ArithmeticException from bigdecimal");
        }
    }
}
 
Example 4
Source Project: flink   File: MemorySize.java    License: Apache License 2.0 5 votes vote down vote up
public MemorySize multiply(double multiplier) {
	checkArgument(multiplier >= 0, "multiplier must be >= 0");

	BigDecimal product = BigDecimal.valueOf(this.bytes).multiply(BigDecimal.valueOf(multiplier));
	if (product.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) > 0) {
		throw new ArithmeticException("long overflow");
	}
	return new MemorySize(product.longValue());
}
 
Example 5
Source Project: gemfirexd-oss   File: SQLDecimal.java    License: Apache License 2.0 5 votes vote down vote up
public int hashCode()
{
	long longVal;
	BigDecimal localValue = getBigDecimal();

	double doubleVal = (localValue != null) ? localValue.doubleValue() : 0;

	if (Double.isInfinite(doubleVal))
	{
		/*
		 ** This loses the fractional part, but it probably doesn't
		 ** matter for numbers that are big enough to overflow a double -
		 ** it's probably rare for numbers this big to be different only in
		 ** their fractional parts.
		 */
		longVal = localValue.longValue();
	}
	else
	{
		longVal = (long) doubleVal;
		if (longVal != doubleVal)
		{
			longVal = Double.doubleToLongBits(doubleVal);
		}
	}

	return (int) (longVal ^ (longVal >> 32));
}
 
Example 6
/**
 * Test FloorMod of long arguments against expected value.
 * The expected value is usually a Long but in some cases  is
 * an ArithmeticException.
 *
 * @param x dividend
 * @param y modulus
 * @param expected expected value
 */
static void testLongFloorMod(long x, long y, Object expected) {
    Object result = doFloorMod(x, y);
    if (!resultEquals(result, expected)) {
        fail("FAIL: long Math.floorMod(%d, %d) = %s; expected %s%n", x, y, result, expected);
    }

    Object strict_result = doStrictFloorMod(x, y);
    if (!resultEquals(strict_result, expected)) {
        fail("FAIL: long StrictMath.floorMod(%d, %d) = %s; expected %s%n", x, y, strict_result, expected);
    }

    try {
        // Verify the result against BigDecimal rounding mode.
        BigDecimal xD = new BigDecimal(x);
        BigDecimal yD = new BigDecimal(y);
        BigDecimal resultD = xD.divide(yD, RoundingMode.FLOOR);
        resultD = resultD.multiply(yD);
        resultD = xD.subtract(resultD);
        long fr = resultD.longValue();
        if (!result.equals(fr)) {
            fail("FAIL: Long.floorMod(%d, %d) = %d is different than BigDecimal result: %d%n", x, y, result, fr);

        }
    } catch (ArithmeticException ae) {
        if (y != 0) {
            fail("FAIL: long Math.floorMod(%d, %d); unexpected ArithmeticException from bigdecimal");
        }
    }
}
 
Example 7
Source Project: flink   File: SqlDateTimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static long divide(long res, BigDecimal value) {
	if (value.equals(BigDecimal.ONE)) {
		return res;
	} else if (value.compareTo(BigDecimal.ONE) < 0 && value.signum() == 1) {
		BigDecimal reciprocal = BigDecimal.ONE.divide(value, RoundingMode.UNNECESSARY);
		return reciprocal.multiply(BigDecimal.valueOf(res)).longValue();
	} else {
		return res / value.longValue();
	}
}
 
Example 8
public static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency) throws UnableToCalculateRateException {
    ExchangeRateProvider rates = db.getHistoryRates();
    BigDecimal income = BigDecimal.ZERO;
    BigDecimal expenses = BigDecimal.ZERO;
    for (TransactionInfo t : list) {
        BigDecimal amount = getAmountFromTransaction(db, t, toCurrency, rates);
        if (amount.signum() > 0) {
            income = income.add(amount);
        } else {
            expenses = expenses.add(amount);
        }
    }
    return new long[]{income.longValue(),expenses.longValue()};
}
 
Example 9
/**
 * Test FloorMod of long arguments against expected value.
 * The expected value is usually a Long but in some cases  is
 * an ArithmeticException.
 *
 * @param x dividend
 * @param y modulus
 * @param expected expected value
 */
static void testLongIntFloorMod(long x, int y, Object expected) {
    Object result = doFloorMod(x, y);
    if (!resultEquals(result, expected)) {
        fail("FAIL: long Math.floorMod(%d, %d) = %s; expected %s%n", x, y, result, expected);
    }

    Object strict_result = doStrictFloorMod(x, y);
    if (!resultEquals(strict_result, expected)) {
        fail("FAIL: long StrictMath.floorMod(%d, %d) = %s; expected %s%n", x, y, strict_result, expected);
    }

    try {
        // Verify the result against BigDecimal rounding mode.
        BigDecimal xD = new BigDecimal(x);
        BigDecimal yD = new BigDecimal(y);
        BigDecimal resultD = xD.divide(yD, RoundingMode.FLOOR);
        resultD = resultD.multiply(yD);
        resultD = xD.subtract(resultD);
        long fr = resultD.longValue();
        if (!result.equals(fr)) {
            fail("FAIL: Long.floorMod(%d, %d) = %d is different than BigDecimal result: %d%n", x, y, result, fr);

        }
    } catch (ArithmeticException ae) {
        if (y != 0) {
            fail("FAIL: long Math.floorMod(%d, %d); unexpected ArithmeticException from bigdecimal");
        }
    }
}
 
Example 10
/**
 * MAKETIME(h,m,s) is a time function that calculates a time value from the
 * total number of hours, minutes, and seconds. Result: Time value
 */
@Override
public boolean getTime(MySQLTime ltime) {
    long minute = args.get(1).valInt().longValue();
    BigDecimal sec = args.get(2).valDecimal();
    if (sec == null || args.get(0).isNullValue() || args.get(1).isNullValue() || args.get(2).isNullValue() ||
            minute < 0 || minute > 59) {
        nullValue = true;
        return true;
    }
    nullValue = false;
    long scdquot = sec.longValue(); // sec can not be null
    long scdrem = (long) ((sec.doubleValue() - scdquot) * 1000000);
    if ((nullValue = (scdquot < 0 || scdquot > 59 || scdrem < 0))) {
        return true;
    }

    ltime.setZeroTime(MySQLTimestampType.MYSQL_TIMESTAMP_TIME);

    long hour = args.get(0).valInt().longValue();
    /* Check for integer overflows */
    if (hour < 0) {
        ltime.setNeg(true);
    }
    ltime.setHour(((hour < 0 ? -hour : hour)));
    ltime.setMinute(minute);
    ltime.setSecond(scdquot);
    ltime.setSecondPart(scdrem);
    return false;
}
 
Example 11
Source Project: flink   File: SqlDateTimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static long mod(long res, BigDecimal value) {
	if (value.equals(BigDecimal.ONE)) {
		return res;
	} else {
		return res % value.longValue();
	}
}
 
Example 12
@Override
public Long createFromBigDecimal(BigDecimal d) {
    return d.longValue();
}
 
Example 13
Source Project: erflute   File: DB2TableImportManager.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Sequence importSequence(String schema, String sequenceName) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
        stmt = con.prepareStatement("SELECT * FROM SYSCAT.SEQUENCES WHERE SEQSCHEMA = ? AND SEQNAME = ?");
        stmt.setString(1, schema);
        stmt.setString(2, sequenceName);

        rs = stmt.executeQuery();

        if (rs.next()) {
            final Sequence sequence = new Sequence();

            sequence.setName(sequenceName);
            sequence.setSchema(schema);
            sequence.setIncrement(rs.getInt("INCREMENT"));
            sequence.setMinValue(rs.getLong("MINVALUE"));

            BigDecimal maxValue = rs.getBigDecimal("MAXVALUE");

            final int dataTypeId = rs.getInt("DATATYPEID");
            String dataType = null;
            if (dataTypeId == 16) {
                dataType = "DECIMAL(p)";
                sequence.setDecimalSize(rs.getInt("PRECISION"));
            } else if (dataTypeId == 24) {
                dataType = "INTEGER";
                if (maxValue.intValue() == Integer.MAX_VALUE) {
                    maxValue = null;
                }
            } else if (dataTypeId == 20) {
                dataType = "BIGINT";
                if (maxValue.longValue() == Long.MAX_VALUE) {
                    maxValue = null;
                }
            } else if (dataTypeId == 28) {
                dataType = "SMALLINT";
                if (maxValue.intValue() == Short.MAX_VALUE) {
                    maxValue = null;
                }
            } else {
                dataType = "";
            }

            sequence.setDataType(dataType);
            sequence.setMaxValue(maxValue);
            sequence.setStart(rs.getLong("START"));
            sequence.setCache(rs.getInt("CACHE"));

            boolean cycle = false;
            if ("Y".equals(rs.getString("CYCLE"))) {
                cycle = true;
            }

            sequence.setCycle(cycle);

            boolean order = false;
            if ("Y".equals(rs.getString("ORDER"))) {
                order = true;
            }

            sequence.setOrder(order);

            return sequence;
        }

        return null;
    } finally {
        close(rs);
        close(stmt);
    }
}
 
Example 14
Source Project: SB_Elsinore_Server   File: CompressorDevice.java    License: MIT License 4 votes vote down vote up
public void setDelay(BigDecimal delay)
{
    delayBetweenRuns = delay.longValue() * 1000 * 60;
}
 
Example 15
@Override
public Byte createFromBigDecimal(BigDecimal d) {
    return (byte) d.longValue();
}
 
Example 16
Source Project: ermasterr   File: DB2TableImportManager.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Sequence importSequence(final String schema, final String sequenceName) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
        stmt = con.prepareStatement("SELECT * FROM SYSIBM.SYSSEQUENCES WHERE SEQSCHEMA = ? AND SEQNAME = ?");
        stmt.setString(1, schema);
        stmt.setString(2, sequenceName);

        rs = stmt.executeQuery();

        if (rs.next()) {
            final Sequence sequence = new Sequence();

            sequence.setName(sequenceName);
            sequence.setSchema(schema);
            sequence.setIncrement(rs.getInt("INCREMENT"));
            sequence.setMinValue(rs.getLong("MINVALUE"));

            BigDecimal maxValue = rs.getBigDecimal("MAXVALUE");

            final int dataTypeId = rs.getInt("DATATYPEID");
            String dataType = null;

            if (dataTypeId == 16) {
                dataType = "DECIMAL(p)";
                sequence.setDecimalSize(rs.getInt("PRECISION"));

            } else if (dataTypeId == 24) {
                dataType = "INTEGER";
                if (maxValue.intValue() == Integer.MAX_VALUE) {
                    maxValue = null;
                }

            } else if (dataTypeId == 20) {
                dataType = "BIGINT";
                if (maxValue.longValue() == Long.MAX_VALUE) {
                    maxValue = null;
                }

            } else if (dataTypeId == 28) {
                dataType = "SMALLINT";
                if (maxValue.intValue() == Short.MAX_VALUE) {
                    maxValue = null;
                }

            } else {
                dataType = "";

            }
            sequence.setDataType(dataType);

            sequence.setMaxValue(maxValue);
            sequence.setStart(rs.getLong("START"));

            final int cache = rs.getInt("CACHE");

            if (cache <= 1) {
                sequence.setNocache(true);
            } else {
                sequence.setCache(cache);
            }

            boolean cycle = false;
            if ("Y".equals(rs.getString("CYCLE"))) {
                cycle = true;
            }

            sequence.setCycle(cycle);

            boolean order = false;
            if ("Y".equals(rs.getString("ORDER"))) {
                order = true;
            }

            sequence.setOrder(order);

            return sequence;
        }

        return null;

    } finally {
        this.close(rs);
        this.close(stmt);
    }
}
 
Example 17
@Override
public Object getParameter(String name, BigDecimal instance) {
  return instance.longValue();
}
 
Example 18
private long roundEven(double value)
{
    BigDecimal bd = new BigDecimal(value);
    bd = bd.round(MathContext.DECIMAL64);
    return bd.longValue();
}
 
Example 19
/**   
* 提供精确的类型转换(Long)   
* @param v 需要被转换的数字   
* @return 返回转换结果   
*/    
public static long convertsToLong(double v){    
    BigDecimal b = new BigDecimal(v);    
    return b.longValue();    
}
 
Example 20
/** Convert from BigDecimal to long
 * @param bd The BigDecimal to convert
 * @return The resulting long
 * @throws Exception if anything goes wrong while doing the conversion.
 */
public static long bigDecimal2Long(BigDecimal bd)
    throws Exception {
    return (bd == null) ? 0 : bd.longValue();
}