public static Number coerceTo(final Number a, final Class<? extends Number> clazz) {
        if (a.getClass().equals(clazz)) {
            return a;
        } else if (clazz.equals(Integer.class)) {
            if (a.longValue() >= Integer.MIN_VALUE && a.longValue() <= Integer.MAX_VALUE) {
                return a.intValue();
            }
        } else if (clazz.equals(Long.class)) {
            return a.longValue();
        } else if (clazz.equals(Float.class)) {
            if (a.doubleValue() >= -Float.MAX_VALUE && a.doubleValue() <= Float.MAX_VALUE) {
                return a.floatValue();
            }
        } else if (clazz.equals(Double.class)) {
            return a.doubleValue();
        } else if (clazz.equals(Byte.class)) {
            if (a.longValue() >= Byte.MIN_VALUE && a.longValue() <= Byte.MAX_VALUE) {
                return a.byteValue();
            }
        } else if (clazz.equals(Short.class)) {
            if (a.longValue() >= Short.MIN_VALUE && a.longValue() <= Short.MAX_VALUE) {
                return a.shortValue();
            }
        } else if (clazz.equals(BigInteger.class)) {
            return NumberHelper.bigIntegerValue(a);
        } else if (clazz.equals(BigDecimal.class)) {
            return NumberHelper.bigDecimalValue(a);
        } else {
            throw new IllegalArgumentException("Unsupported numeric type: " + clazz);
        }

        // return as-is since it didn't fit the type we wanted to coerce to
        return a;
    }
Coerces the given number to the specified numeric type if it can fit into it.
Otherwise, retains the original type.

@param a the number to be coerced
@param clazz the target numeric type class
@return the coerced number in the specified type or the original type if it cannot fit
@throws IllegalArgumentException if the specified numeric type is unsupported
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/util/NumberHelper.java