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

The following examples show how to use java.math.BigDecimal#longValueExact() . 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: phoenix   File: ParseNodeFactory.java    License: Apache License 2.0 6 votes vote down vote up
public LiteralParseNode wholeNumber(String text) {
    int length = text.length();
    // We know it'll fit into long, might still fit into int
    if (length <= PDataType.LONG_PRECISION-1) {
        long l = Long.parseLong(text);
        if (l <= Integer.MAX_VALUE) {
            // Fits into int
            return new LiteralParseNode((int)l);
        }
        return new LiteralParseNode(l);
    }
    // Might still fit into long
    BigDecimal d = new BigDecimal(text, PDataType.DEFAULT_MATH_CONTEXT);
    if (d.compareTo(MAX_LONG) <= 0) {
        return new LiteralParseNode(d.longValueExact());
    }
    // Doesn't fit into long
    return new LiteralParseNode(d);
}
 
Example 2
Source Project: tddl   File: EnumeratorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将BigDecimal转换为long或者double
 * 
 * @param big
 * @return
 */
public static Comparable<?> toPrimaryValue(Comparable<?> comp) {

    if (comp instanceof BigDecimal) {
        BigDecimal big = (BigDecimal) comp;
        int scale = big.scale();
        if (scale == 0) {
            // long int
            try {
                return big.longValueExact();
            } catch (ArithmeticException e) {
                return big;
            }
        } else {
            // double float
            return big.doubleValue();
        }
    } else {
        return comp;
    }

}
 
Example 3
Source Project: phoenix   File: PTime.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public java.sql.Time toObject(byte[] b, int o, int l, PDataType actualType, SortOrder sortOrder,
    Integer maxLength, Integer scale) {
  if (l == 0) {
    return null;
  }
  if (equalsAny(actualType, PTimestamp.INSTANCE, PUnsignedTimestamp.INSTANCE, PDate.INSTANCE,
      PUnsignedDate.INSTANCE, PTime.INSTANCE, PUnsignedTime.INSTANCE, PLong.INSTANCE,
      PUnsignedLong.INSTANCE)) {
    return new java.sql.Time(actualType.getCodec().decodeLong(b, o, sortOrder));
  } else if (actualType == PDecimal.INSTANCE) {
    BigDecimal bd = (BigDecimal) actualType.toObject(b, o, l, actualType, sortOrder);
    return new java.sql.Time(bd.longValueExact());
  }
  throwConstraintViolationException(actualType, this);
  return null;
}
 
Example 4
public final static long longValue(long addr) {
    byte type = Unsafe.getByte(addr);
    if (type == Value.FORMAT_INT4) {
        return Int4.get(addr);
    }
    else if (type == Value.FORMAT_INT8) {
        return Int8.get(null, addr);
    }
    else if (type == Value.FORMAT_DECIMAL) {
        BigDecimal dec = FishDecimal.get(null, addr);
        return dec.longValueExact();
    }
    else {
        throw new ArithmeticException();
    }
}
 
Example 5
Source Project: tddl5   File: EnumeratorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将BigDecimal转换为long或者double
 * 
 * @param big
 * @return
 */
public static Comparable<?> toPrimaryValue(Comparable<?> comp) {

    if (comp instanceof BigDecimal) {
        BigDecimal big = (BigDecimal) comp;
        int scale = big.scale();
        if (scale == 0) {
            // long int
            try {
                return big.longValueExact();
            } catch (ArithmeticException e) {
                return big;
            }
        } else {
            // double float
            return big.doubleValue();
        }
    } else {
        return comp;
    }

}
 
Example 6
/**
 * Build a Java <code>long</code> from a fixed point decimal byte representation.
 *
 * @throws IllegalArgumentException if the specified representation is not recognized.
 * @throws ArithmeticException if value is too large for a long
 */
public static long getLong(byte[] buffer,
                           int offset,
                           int precision,
                           int scale) throws java.io.UnsupportedEncodingException {
    if (precision > Limits.DB2_MAX_DECIMAL_PRECISION_SCALE) {
        // throw an exception here if nibbles is greater than 38
        throw new java.lang.IllegalArgumentException(
            msgutil.getTextMessage(SQLState.DECIMAL_TOO_MANY_DIGITS));
    }

    // The byte-length of a packed decimal with precision <code>p</code> is always <code>p/2 + 1</code>
    int length = precision / 2 + 1;

    // check for sign.
    int signum;
    if ((buffer[offset + length - 1] & 0x0F) == 0x0D) {
        signum = -1;
    } else {
        signum = 1;
    }

    if (precision - scale <= 18) {
        // Can be handled by long without overflow.
        // Compute the integer part only.
        int leftOfDecimalPoint = length * 2 - 1 - scale;
        return signum * packedNybblesToLong(buffer, offset, 0,
                                            leftOfDecimalPoint);
    } else {
        // Strip off fraction part by converting via BigInteger
        // lest longValueExact will throw ArithmeticException
        BigDecimal tmp = new BigDecimal(
            getBigDecimal(buffer, offset, precision, scale).toBigInteger());
        // throws ArithmeticException if overflow:
        return tmp.longValueExact();
    }
}
 
Example 7
Source Project: DataFixerUpper   File: JsonOps.java    License: MIT License 5 votes vote down vote up
@Override
public <U> U convertTo(final DynamicOps<U> outOps, final JsonElement input) {
    if (input instanceof JsonObject) {
        return convertMap(outOps, input);
    }
    if (input instanceof JsonArray) {
        return convertList(outOps, input);
    }
    if (input instanceof JsonNull) {
        return outOps.empty();
    }
    final JsonPrimitive primitive = input.getAsJsonPrimitive();
    if (primitive.isString()) {
        return outOps.createString(primitive.getAsString());
    }
    if (primitive.isBoolean()) {
        return outOps.createBoolean(primitive.getAsBoolean());
    }
    final BigDecimal value = primitive.getAsBigDecimal();
    try {
        final long l = value.longValueExact();
        if ((byte) l == l) {
            return outOps.createByte((byte) l);
        }
        if ((short) l == l) {
            return outOps.createShort((short) l);
        }
        if ((int) l == l) {
            return outOps.createInt((int) l);
        }
        return outOps.createLong(l);
    } catch (final ArithmeticException e) {
        final double d = value.doubleValue();
        if ((float) d == d) {
            return outOps.createFloat((float) d);
        }
        return outOps.createDouble(d);
    }
}
 
Example 8
Source Project: jsr354-ri   File: RoundedMoney.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isOne(Number number) {
    BigDecimal bd = MoneyUtils.getBigDecimal(number);
    try {
        return bd.scale() == 0 && bd.longValueExact() == 1L;
    } catch (Exception e) {
        // The only way to end up here is that longValueExact throws an ArithmeticException,
        // so the amount is definitively not equal to 1.
        return false;
    }
}
 
Example 9
Source Project: big-math   File: BigDecimalMath.java    License: MIT License 5 votes vote down vote up
/**
 * Calculates {@link BigDecimal} x to the power of {@link BigDecimal} y (x<sup>y</sup>).
 * 
 * @param x the {@link BigDecimal} value to take to the power
 * @param y the {@link BigDecimal} value to serve as exponent
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated x to the power of y with the precision specified in the <code>mathContext</code>
 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
 * @see #pow(BigDecimal, long, MathContext)
 */
public static BigDecimal pow(BigDecimal x, BigDecimal y, MathContext mathContext) {
	checkMathContext(mathContext);
	if (x.signum() == 0) {
		switch (y.signum()) {
			case 0 : return round(ONE, mathContext);
			case 1 : return round(ZERO, mathContext);
		}
	}

	// TODO optimize y=0, y=1, y=10^k, y=-1, y=-10^k

	try {
		long longValue = y.longValueExact();
		return pow(x, longValue, mathContext);
	} catch (ArithmeticException ex) {
		// ignored
	}
	
	if (fractionalPart(y).signum() == 0) {
		return powInteger(x, y, mathContext);
	}

	// x^y = exp(y*log(x))
	MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode());
	BigDecimal result = exp(y.multiply(log(x, mc), mc), mc);

	return round(result, mathContext);
}
 
Example 10
Source Project: phoenix   File: PLong.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Object toObject(Object object, PDataType actualType) {
    if (object == null) {
        return null;
    }
    long s;
    if (equalsAny(actualType, PLong.INSTANCE, PUnsignedLong.INSTANCE)) {
        return object;
    } else if (equalsAny(actualType, PUnsignedInt.INSTANCE,
            PInteger.INSTANCE)) {
        s = (Integer) object;
        return s;
    } else if (equalsAny(actualType, PTinyint.INSTANCE, PUnsignedTinyint.INSTANCE)) {
        s = (Byte) object;
        return s;
    } else if (equalsAny(actualType, PSmallint.INSTANCE, PUnsignedSmallint.INSTANCE)) {
        s = (Short) object;
        return s;
    } else if (equalsAny(actualType, PFloat.INSTANCE, PUnsignedFloat.INSTANCE)) {
        Float f = (Float) object;
        if (f > Long.MAX_VALUE || f < Long.MIN_VALUE) {
            throw newIllegalDataException(
                    actualType + " value " + f + " cannot be cast to Long without changing its value");
        }
        s = f.longValue();
        return s;
    } else if (equalsAny(actualType, PDouble.INSTANCE, PUnsignedDouble.INSTANCE)) {
        Double de = (Double) object;
        if (de > Long.MAX_VALUE || de < Long.MIN_VALUE) {
            throw newIllegalDataException(
                    actualType + " value " + de + " cannot be cast to Long without changing its value");
        }
        s = de.longValue();
        return s;
    } else if (actualType == PDecimal.INSTANCE) {
        BigDecimal d = (BigDecimal) object;
        return d.longValueExact();
    } else if (equalsAny(actualType, PDate.INSTANCE, PUnsignedDate.INSTANCE, PTime.INSTANCE,
            PUnsignedTime.INSTANCE)) {
        java.util.Date date = (java.util.Date) object;
        return date.getTime();
    }
    return throwConstraintViolationException(actualType, this);
}
 
Example 11
public static Operator genLiteralValue(GeneratorContext ctx, Planner planner, Literal_valueContext rule) {
    if (rule.literal_string() != null) {
        return genString(ctx, planner, rule.literal_string());
    }
    else if (rule.literal_interval() != null) {
        return parseInterval(ctx, planner, rule.literal_interval());
    }
    TerminalNode token = (TerminalNode) rule.getChild(0);
    switch (token.getSymbol().getType()) {
    case MysqlParser.NUMERIC_LITERAL: {
        BigDecimal bd = new BigDecimal(rule.getText());
        try {
            return new LongValue(bd.longValueExact());
        }
        catch (Exception ignored) {
        }
        return new NumericValue(new BigDecimal(rule.getText()));
    }
    case MysqlParser.K_NULL:
        return new NullValue();
    case MysqlParser.K_CURRENT_DATE:
        return new SysDate();
    case MysqlParser.K_CURRENT_TIME:
        return new CurrentTime();
    case MysqlParser.K_CURRENT_TIMESTAMP:
        return new CurrentTimestamp();
    case MysqlParser.K_TRUE:
        return new LongValue(1);
    case MysqlParser.K_FALSE:
        return new LongValue(0);
    case MysqlParser.BLOB_LITERAL:
        String text = rule.BLOB_LITERAL().getText();
        return new BytesValue(mysqlXBinaryToBytes(text));
    case MysqlParser.HEX_LITERAL:
        String hextxt = rule.HEX_LITERAL().getText();
        hextxt = hextxt.substring(2, hextxt.length());
        if (hextxt.length() == 0) {
            return new BytesValue(new byte[0]);
        }
        return new BytesValue(BytesUtil.hexToBytes(hextxt));
    default:
        throw new NotImplementedException();
    }
}
 
Example 12
Source Project: dekaf   File: Numbers.java    License: Apache License 2.0 4 votes vote down vote up
@Contract(value = "!null -> !null; null -> null", pure = true)
public static Number convertNumberSmartly(final BigDecimal decimal) {
  if (decimal == null) return null;
  if (decimal.equals(Numbers.DECIMAL_ZERO)) return BYTE_ZERO;

  final int precision = decimal.precision();
  final int scale = decimal.scale();

  Number num;
  if (scale == 0) {
    try {
      if (precision <= 19 && decimal.compareTo(Numbers.DECIMAL_MIN_LONG) >= 0
                          && decimal.compareTo(Numbers.DECIMAL_MAX_LONG) <= 0) {
        long v = decimal.longValueExact();
        if (-128 <= v && v <= 127) num = (byte) v;
        else if (-32768 <= v && v <= 32767) num = (short) v;
        else if (Integer.MIN_VALUE <= v && v <= Integer.MAX_VALUE) num = (int) v;
        else num = v;
      }
      else {
        num = decimal.toBigIntegerExact();
      }
    }
    catch (ArithmeticException ae) {
      num = decimal;
    }
  }
  else {
    if (precision <= 6) {
      num = decimal.floatValue();
    }
    else if (precision <= 15) {
      num = decimal.doubleValue();
    }
    else {
      num = decimal;
    }
  }

  return num;
}
 
Example 13
Source Project: java-stellar-sdk   File: Operation.java    License: Apache License 2.0 4 votes vote down vote up
protected static long toXdrAmount(String value) {
  value = checkNotNull(value, "value cannot be null");
  BigDecimal amount = new BigDecimal(value).multiply(Operation.ONE);
  return amount.longValueExact();
}
 
Example 14
/**
 * Converts a fraction from 0 to 1 for this field to a value.
 * <p>
 * The fractional value must be between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The value is obtained by calculation from the field range and a rounding
 * mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the fractional second-of-minute of 0.25 would be converted to 15,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param fraction  the fraction to convert, not null
 * @return the value of the field, valid for this rule
 * @throws DateTimeException if the value cannot be converted
 */
private long convertFromFraction(BigDecimal fraction) {
    ValueRange range = field.range();
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
    return valueBD.longValueExact();
}
 
Example 15
/**
 * Converts a fraction from 0 to 1 for this field to a value.
 * <p>
 * The fractional value must be between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The value is obtained by calculation from the field range and a rounding
 * mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the fractional second-of-minute of 0.25 would be converted to 15,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param fraction  the fraction to convert, not null
 * @return the value of the field, valid for this rule
 * @throws DateTimeException if the value cannot be converted
 */
private long convertFromFraction(BigDecimal fraction) {
    ValueRange range = field.range();
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
    return valueBD.longValueExact();
}
 
Example 16
/**
 * Converts a fraction from 0 to 1 for this field to a value.
 * <p>
 * The fractional value must be between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The value is obtained by calculation from the field range and a rounding
 * mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the fractional second-of-minute of 0.25 would be converted to 15,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param fraction  the fraction to convert, not null
 * @return the value of the field, valid for this rule
 * @throws DateTimeException if the value cannot be converted
 */
private long convertFromFraction(BigDecimal fraction) {
    ValueRange range = field.range();
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
    return valueBD.longValueExact();
}
 
Example 17
/**
 * Converts a fraction from 0 to 1 for this field to a value.
 * <p>
 * The fractional value must be between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link TemporalField#range() value range} is fixed.
 * The value is obtained by calculation from the field range and a rounding
 * mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the fractional second-of-minute of 0.25 would be converted to 15,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param fraction  the fraction to convert, not null
 * @return the value of the field, valid for this rule
 * @throws DateTimeException if the value cannot be converted
 */
private long convertFromFraction(BigDecimal fraction) {
    ValueRange range = field.range();
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
    return valueBD.longValueExact();
}
 
Example 18
/**
 * Converts a fraction from 0 to 1 for this field to a value.
 * <p>
 * The fractional value must be between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The value is obtained by calculation from the field range and a rounding
 * mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the fractional second-of-minute of 0.25 would be converted to 15,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param fraction  the fraction to convert, not null
 * @return the value of the field, valid for this rule
 * @throws DateTimeException if the value cannot be converted
 */
private long convertFromFraction(BigDecimal fraction) {
    ValueRange range = field.range();
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
    return valueBD.longValueExact();
}
 
Example 19
private Number convertWithBigDecimal(final Class<? extends Number> type, final BigDecimal number, final String str) {
    
    if(Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        return lenient ? number.byteValue() : number.byteValueExact();
        
    } else if(Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        return lenient ? number.shortValue() : number.shortValueExact();
        
    } else if(Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        return lenient ? number.intValue() : number.intValueExact();
        
    } else if(Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        return lenient ? number.longValue() : number.longValueExact();
        
    } else if(Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        return number.floatValue();
        
    } else if(Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        return number.doubleValue();
        
    } else if(type.isAssignableFrom(BigInteger.class)) {
        return lenient ? number.toBigInteger() : number.toBigIntegerExact();
        
    } else if(type.isAssignableFrom(BigDecimal.class)) {
        return number;
        
    }
    
    throw new IllegalArgumentException(String.format("not support class type : %s", type.getCanonicalName()));
    
}
 
Example 20
private Number parseFromBigDecimal(final Class<? extends Number> type, final BigDecimal number) {
    
    if(Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        return lenient ? number.byteValue() : number.byteValueExact();
        
    } else if(Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        return lenient ? number.shortValue() : number.shortValueExact();
        
    } else if(Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        return lenient ? number.intValue() : number.intValueExact();
        
    } else if(Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        return lenient ? number.longValue() : number.longValueExact();
        
    } else if(Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        return number.floatValue();
        
    } else if(Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        return number.doubleValue();
        
    } else if(type.isAssignableFrom(BigInteger.class)) {
        return lenient ? number.toBigInteger() : number.toBigIntegerExact();
        
    } else if(type.isAssignableFrom(BigDecimal.class)) {
        return number;
        
    }
    
    throw new IllegalArgumentException(String.format("Not support class type : %s", type.getCanonicalName()));
    
}