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

The following examples show how to use java.math.BigDecimal#intValueExact() . 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: JsonValueReader.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override public int nextInt() throws IOException {
  Object peeked = require(Object.class, Token.NUMBER);

  int result;
  if (peeked instanceof Number) {
    result = ((Number) peeked).intValue();
  } else if (peeked instanceof String) {
    try {
      result = Integer.parseInt((String) peeked);
    } catch (NumberFormatException e) {
      try {
        BigDecimal asDecimal = new BigDecimal((String) peeked);
        result = asDecimal.intValueExact();
      } catch (NumberFormatException e2) {
        throw typeMismatch(peeked, Token.NUMBER);
      }
    }
  } else {
    throw typeMismatch(peeked, Token.NUMBER);
  }
  remove();
  return result;
}
 
Example 2
Source File: FlinkReturnTypes.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = FlinkTypeSystem.inferRoundType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 3
Source File: PInteger.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public Integer toObject(byte[] b, int o, int l, PDataType actualType,
    SortOrder sortOrder, Integer maxLength, Integer scale) {
  if (l == 0) {
    return null;
  }
  if (equalsAny(actualType, PLong.INSTANCE, PUnsignedLong.INSTANCE, PInteger.INSTANCE,
      PUnsignedInt.INSTANCE, PSmallint.INSTANCE, PUnsignedSmallint.INSTANCE, PTinyint.INSTANCE,
      PUnsignedTinyint.INSTANCE, PFloat.INSTANCE, PUnsignedFloat.INSTANCE, PDouble.INSTANCE,
      PUnsignedDouble.INSTANCE)) {
    return actualType.getCodec().decodeInt(b, o, sortOrder);
  } else if (actualType == PDecimal.INSTANCE) {
    BigDecimal bd = (BigDecimal) actualType.toObject(b, o, l, actualType, sortOrder);
    return bd.intValueExact();
  }
  throwConstraintViolationException(actualType, this);
  return null;
}
 
Example 4
Source File: ParseSupport.java    From curiostack with MIT License 6 votes vote down vote up
/** Parsers an int32 value out of the input. */
public static int parseInt32(JsonParser parser) throws IOException {
  JsonToken token = parser.currentToken();
  if (token == JsonToken.VALUE_NUMBER_INT) {
    // Use optimized code path for integral primitives, the normal case.
    return parser.getIntValue();
  }
  // JSON doesn't distinguish between integer values and floating point values so "1" and
  // "1.000" are treated as equal in JSON. For this reason we accept floating point values for
  // integer fields as well as long as it actually is an integer (i.e., round(value) == value).
  try {
    BigDecimal value =
        new BigDecimal(
            parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength());
    return value.intValueExact();
  } catch (Exception e) {
    throw new InvalidProtocolBufferException("Not an int32 value: " + parser.getText());
  }
}
 
Example 5
Source File: FlinkReturnTypes.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = LogicalTypeMerging.findRoundDecimalType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 6
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Returns whether the specified {@link BigDecimal} value can be represented as <code>int</code>.
 *
 * <p>If this returns <code>true</code> you can call {@link BigDecimal#intValueExact()} without fear of an {@link ArithmeticException}.</p>
 *
 * @param value the {@link BigDecimal} to check
 * @return <code>true</code> if the value can be represented as <code>int</code> value
 */
public static boolean isIntValue(BigDecimal value) {
	// TODO impl isIntValue() without exceptions
	try {
		value.intValueExact();
		return true;
	} catch (ArithmeticException ex) {
		// ignored
	}
	return false;
}
 
Example 7
Source File: JsonStreamDocumentReader.java    From ojai with Apache License 2.0 5 votes vote down vote up
@Override
public int getDecimalValueAsInt() {
  BigDecimal decimal = getDecimal();
  if (decimal != null) {
    return decimal.intValueExact();
  }
  return 0;
}
 
Example 8
Source File: TypeIntrospections.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
boolean isMaxViolated(Object value, BigDecimal max) {
    if (max == null) {
        return false;
    }
    return ((String) value).length() > max.intValueExact();
}
 
Example 9
Source File: TypeIntrospections.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
boolean isMaxViolated(Object value, BigDecimal max) {
    if (max == null) {
        return false;
    }
    return ((String) value).length() > max.intValueExact();
}
 
Example 10
Source File: TypeUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
public static int intValue(BigDecimal decimal) {
    if (decimal == null) {
        return 0;
    }

    int scale = decimal.scale();
    if (scale >= -100 && scale <= 100) {
        return decimal.intValue();
    }

    return decimal.intValueExact();
}
 
Example 11
Source File: SqlCallBinding.java    From calcite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override public int getIntLiteralOperand(int ordinal) {
  SqlNode node = call.operand(ordinal);
  final Object o = SqlLiteral.value(node);
  if (o instanceof BigDecimal) {
    BigDecimal bd = (BigDecimal) o;
    try {
      return bd.intValueExact();
    } catch (ArithmeticException e) {
      throw SqlUtil.newContextException(node.pos,
          RESOURCE.numberLiteralOutOfRange(bd.toString()));
    }
  }
  throw new AssertionError();
}
 
Example 12
Source File: ProjectItemTerm.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Property()
public Integer getPercentageOfTotalBudget(){
    if (getProjectItem().getBudgetedAmount()==null || getProjectItem().getBudgetedAmount().compareTo(BigDecimal.ZERO) == 0) return 0;
    BigDecimal fraction = getBudgetedAmount().divide(getProjectItem().getBudgetedAmount(), MathContext.DECIMAL64);
    BigDecimal percentageAsBd = fraction.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP);
    return percentageAsBd.intValueExact();
}
 
Example 13
Source File: TypeIntrospections.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
boolean isMinViolated(Object value, BigDecimal min) {
    if (min == null) {
        return false;
    }
    return ((String) value).length() < min.intValueExact();
}
 
Example 14
Source File: SqlCallBinding.java    From Bats with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override public int getIntLiteralOperand(int ordinal) {
  SqlNode node = call.operand(ordinal);
  final Object o = SqlLiteral.value(node);
  if (o instanceof BigDecimal) {
    BigDecimal bd = (BigDecimal) o;
    try {
      return bd.intValueExact();
    } catch (ArithmeticException e) {
      throw SqlUtil.newContextException(node.pos,
          RESOURCE.numberLiteralOutOfRange(bd.toString()));
    }
  }
  throw new AssertionError();
}
 
Example 15
Source File: DataTypes.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
public static Integer convertToInteger(final Object value)
{
	if (value == null)
	{
		return null;
	}
	else if (value instanceof Integer)
	{
		return (Integer)value;
	}
	else if (value instanceof String)
	{
		final String valueStr = (String)value;
		if (valueStr.isEmpty())
		{
			return null;
		}

		final BigDecimal valueBD = new BigDecimal(valueStr);
		return valueBD.intValueExact();
	}
	else if (value instanceof Number)
	{
		return ((Number)value).intValue();
	}
	else if (value instanceof LookupValue)
	{
		return ((LookupValue)value).getIdAsInt();
	}
	else if (value instanceof JSONLookupValue)
	{
		return ((JSONLookupValue)value).getKeyAsInt();
	}
	else if (value instanceof Map)
	{
		@SuppressWarnings("unchecked")
		final Map<String, Object> map = (Map<String, Object>)value;
		final IntegerLookupValue lookupValue = JSONLookupValue.integerLookupValueFromJsonMap(map);
		return lookupValue.getIdAsInt();
	}
	else if (value instanceof RepoIdAware)
	{
		return ((RepoIdAware)value).getRepoId();
	}
	else
	{
		throw new ValueConversionException()
				.setFromValue(value)
				.setTargetType(Integer.class);
	}
}
 
Example 16
Source File: IntegerCellConverterFactory.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
@Override
protected Integer convertTypeValue(final BigDecimal value) throws NumberFormatException, ArithmeticException {
    // 少数以下を四捨五入
    BigDecimal decimal = value.setScale(0, RoundingMode.HALF_UP);
    return decimal.intValueExact();
}
 
Example 17
Source File: Manipulator.java    From ldparteditor with MIT License 4 votes vote down vote up
public static void setSnap(BigDecimal trans, BigDecimal rot, BigDecimal scale) {

        try {
            rot.intValueExact();
            switch (rot.intValue()) {
            case 90:
                snap_x_RotateFlag = RotationSnap.DEG90;
                break;
            case 180:
                snap_x_RotateFlag = RotationSnap.DEG180;
                break;
            case 270:
                snap_x_RotateFlag = RotationSnap.DEG270;
                break;
            case 360:
                snap_x_RotateFlag = RotationSnap.DEG360;
                break;
            default:
                snap_x_RotateFlag = RotationSnap.COMPLEX;
                break;
            }

            switch (rot.intValue()) {
            case 90:
                snap_y_RotateFlag = RotationSnap.DEG90;
                break;
            case 180:
                snap_y_RotateFlag = RotationSnap.DEG180;
                break;
            case 270:
                snap_y_RotateFlag = RotationSnap.DEG270;
                break;
            case 360:
                snap_y_RotateFlag = RotationSnap.DEG360;
                break;
            default:
                snap_y_RotateFlag = RotationSnap.COMPLEX;
                break;
            }

            switch (rot.intValue()) {
            case 90:
                snap_z_RotateFlag = RotationSnap.DEG90;
                break;
            case 180:
                snap_z_RotateFlag = RotationSnap.DEG180;
                break;
            case 270:
                snap_z_RotateFlag = RotationSnap.DEG270;
                break;
            case 360:
                snap_z_RotateFlag = RotationSnap.DEG360;
                break;
            default:
                snap_z_RotateFlag = RotationSnap.COMPLEX;
                break;
            }

            switch (rot.intValue()) {
            case 90:
                snap_v_RotateFlag = RotationSnap.DEG90;
                break;
            case 180:
                snap_v_RotateFlag = RotationSnap.DEG180;
                break;
            case 270:
                snap_v_RotateFlag = RotationSnap.DEG270;
                break;
            case 360:
                snap_v_RotateFlag = RotationSnap.DEG360;
                break;
            default:
                snap_v_RotateFlag = RotationSnap.COMPLEX;
                break;
            }
        } catch (ArithmeticException ae) {
            snap_x_RotateFlag = RotationSnap.COMPLEX;
            snap_y_RotateFlag = RotationSnap.COMPLEX;
            snap_z_RotateFlag = RotationSnap.COMPLEX;
            snap_v_RotateFlag = RotationSnap.COMPLEX;
        }

        rot = rot.divide(new BigDecimal(180), Threshold.mc).multiply(new BigDecimal(Math.PI));
        snap_x_Translate = trans;
        snap_y_Translate = trans;
        snap_z_Translate = trans;

        factor_Scale = scale;

        snap_x_Rotate = rot;
        snap_y_Rotate = rot;
        snap_z_Rotate = rot;
        snap_v_Rotate = rot;

    }
 
Example 18
Source File: SimpleNumberFormatter.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
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()));
    
}
 
Example 19
Source File: NumberFormatWrapper.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
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
Source File: DataWord.java    From ethereumj with MIT License 2 votes vote down vote up
/**
 * Converts this DataWord to an int, checking for lost information. 
 * If this DataWord is out of the possible range for an int result 
 * then an ArithmeticException is thrown.
 * 
 * @return this DataWord converted to an int.
 * @throws ArithmeticException - if this will not fit in an int.
 */
public int intValue() {
	BigDecimal tmpValue = new BigDecimal(this.value());
	return tmpValue.intValueExact();
}