com.tukeof.common.util.NumberUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-core Show documentation
Show all versions of common-core Show documentation
a common and useful pure java library
The newest version!
package com.tukeof.common.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.function.BiFunction;
public class NumberUtil {
public static T multiply(Number lhs, Number rhs, Class clazz) {
return computer(lhs, rhs, clazz, BigDecimal::multiply);
}
public static T divide(Number lhs, Number rhs, Class clazz) {
return computer(lhs, rhs, clazz, BigDecimal::divide);
}
public static T subtract(Number lhs, Number rhs, Class clazz) {
return computer(lhs, rhs, clazz, BigDecimal::subtract);
}
public static T add(Number lhs, Number rhs, Class clazz) {
return computer(lhs, rhs, clazz, BigDecimal::add);
}
@SuppressWarnings("unchecked")
private static T toNumber(BigDecimal bigDecimal, Class clazz)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
if (clazz.equals(Integer.class)) {
Method method = clazz.getMethod("valueOf", int.class);
return (T) method.invoke(null, bigDecimal.intValue());
} else if (clazz.equals(Double.class)) {
Method method = clazz.getMethod("valueOf", double.class);
return (T) method.invoke(null, bigDecimal.doubleValue());
} else if (clazz.equals(Long.class)) {
Method method = clazz.getMethod("valueOf", long.class);
return (T) method.invoke(null, bigDecimal.longValue());
} else if (clazz.equals(Float.class)) {
Method method = clazz.getMethod("valueOf", float.class);
return (T) method.invoke(null, bigDecimal.floatValue());
} else {
throw new IllegalArgumentException("args clazz is wrong");
}
}
private static T computer(Number lhs, Number rhs, Class clazz, BiFunction function) {
BigDecimal bd1 = new BigDecimal(lhs.toString());
BigDecimal bd2 = new BigDecimal(rhs.toString());
BigDecimal result = function.apply(bd1, bd2);
try {
return toNumber(result, clazz);
} catch (Throwable t) {
throw new RuntimeException(t.getMessage(), t);
}
}
}