NumberUtils.java

/**
 * Copyright 2014 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

package org.genesys.util;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class NumberUtils {

	public static final Logger LOG = LoggerFactory.getLogger(NumberUtils.class);
	private static Pattern digits = Pattern.compile("\\d+");

	/**
	 * Utility to parse doubles
	 *
	 * @param doubleString
	 * @param factor
	 * @return
	 */
	public static Double parseDouble(final String doubleString, final double factor) {
		if (StringUtils.isBlank(doubleString)) {
			return null;
		}

		try {
			return Double.parseDouble(doubleString) / factor;
		} catch (final NumberFormatException e) {
			LOG.warn("Parse error: {}", doubleString);
			return null;
		}
	}

	/**
	 * Utility to parse doubles, but ignores "0" values
	 *
	 * @param doubleString
	 * @param factor
	 * @return
	 */
	public static Double parseDoubleIgnore0(final String doubleString, final double factor) {
		if (StringUtils.isBlank(doubleString) || doubleString.trim().equals("0")) {
			return null;
		}

		try {
			return Double.parseDouble(doubleString) / factor;
		} catch (final NumberFormatException e) {
			LOG.warn("Parse error: {}", doubleString);
			return null;
		}
	}

	/**
	 * Compare two Integers, Longs, or whatever
	 */
	public static <T> boolean areEqual(T a, T b) {
		return a == null && b == null || a != null && a.equals(b) || b != null && b.equals(a);
	}

	/**
	 * Extract decimal number from a String.
	 */
	public static float numericValue(String input) {
		float v = 0.0f;
		if (StringUtils.isBlank(input))
			return v;

		Matcher m = digits.matcher(input);
		// integer
		if (m.find()) {
			v += Long.parseLong(m.group());
		}
		// decimals
		if (m.find()) {
			float d = Long.parseLong(m.group());
			for (int i = m.group().length(); i > 0; i--) {
				d /= 10;
			}
			v += d;
		}

		return v;
	}

	/**
	 * UUID from byte[]
	 */
	public static UUID toUUID(byte[] data) {
		long msb = 0;
		long lsb = 0;
		assert data.length == 16 : "data must be 16 bytes in length";
		for (int i = 0; i < 8; i++)
			msb = (msb << 8) | (data[i] & 0xff);
		for (int i = 8; i < 16; i++)
			lsb = (lsb << 8) | (data[i] & 0xff);
		return new UUID(msb, lsb);
	}
}