All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xlrit.gears.base.util.NumericUtils Maven / Gradle / Ivy

There is a newer version: 1.17.5
Show newest version
package com.xlrit.gears.base.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

import jakarta.annotation.Nonnull;

public class NumericUtils {
	public static  Long toLong(A a) {
		if (a == null)
			return null;
		else if (a instanceof Long)
			return (Long) a;
		else if (a instanceof Integer)
			return Long.valueOf((Integer) a);
		else if (a instanceof BigDecimal)
			return ((BigDecimal) a).setScale(0, RoundingMode.HALF_UP).longValue();
		else
			throw new RuntimeException("Cannot convert value to Long: " + a);
	}

	public static  BigDecimal toBigDecimal(A a) {
		if (a == null)
			return null;
		else if (a instanceof BigDecimal)
			return (BigDecimal) a;
		else if (a instanceof Long)
			return BigDecimal.valueOf((Long) a);
		else if (a instanceof Integer)
			return BigDecimal.valueOf((Integer) a);
		else
			return BigDecimal.valueOf(a.doubleValue());
	}

	public static int compare(@Nonnull Number a, @Nonnull Number b) {
		if (a instanceof BigDecimal || b instanceof BigDecimal) {
			return toBigDecimal(a).compareTo(toBigDecimal(b));
		}
		if (a instanceof Double || b instanceof Double) {
			return Double.compare(a.doubleValue(), b.doubleValue());
		}
		if (a instanceof Long || b instanceof Long) {
			return Long.compare(a.longValue(), b.longValue());
		}
		throw new IllegalStateException("Unsupported numberic types: a=" + a.getClass() + ", b=" + b.getClass());
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy