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

com.fitbur.apache.commons.lang.math.NumberUtils Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in com.fitburpliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.com.fitbur/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 com.fitbur.apache.com.fitburmons.lang.math;

import java.math.BigDecimal;
import java.math.BigInteger;

import com.fitbur.apache.com.fitburmons.lang.StringUtils;

/**
 * 

Provides extra functionality for Java Number classes.

* * @author Apache Software Foundation * @author Rand McNeely * @author Steve Downey * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author Gary Gregory * @author Fredrik Westermarck * @since 2.0 * @version $Id: NumberUtils.java 1056853 2011-01-09 01:07:04Z niallp $ */ public class NumberUtils { /** Reusable Long constant for zero. */ public static final Long LONG_ZERO = new Long(0L); /** Reusable Long constant for one. */ public static final Long LONG_ONE = new Long(1L); /** Reusable Long constant for minus one. */ public static final Long LONG_MINUS_ONE = new Long(-1L); /** Reusable Integer constant for zero. */ public static final Integer INTEGER_ZERO = new Integer(0); /** Reusable Integer constant for one. */ public static final Integer INTEGER_ONE = new Integer(1); /** Reusable Integer constant for minus one. */ public static final Integer INTEGER_MINUS_ONE = new Integer(-1); /** Reusable Short constant for zero. */ public static final Short SHORT_ZERO = new Short((short) 0); /** Reusable Short constant for one. */ public static final Short SHORT_ONE = new Short((short) 1); /** Reusable Short constant for minus one. */ public static final Short SHORT_MINUS_ONE = new Short((short) -1); /** Reusable Byte constant for zero. */ public static final Byte BYTE_ZERO = new Byte((byte) 0); /** Reusable Byte constant for one. */ public static final Byte BYTE_ONE = new Byte((byte) 1); /** Reusable Byte constant for minus one. */ public static final Byte BYTE_MINUS_ONE = new Byte((byte) -1); /** Reusable Double constant for zero. */ public static final Double DOUBLE_ZERO = new Double(0.0d); /** Reusable Double constant for one. */ public static final Double DOUBLE_ONE = new Double(1.0d); /** Reusable Double constant for minus one. */ public static final Double DOUBLE_MINUS_ONE = new Double(-1.0d); /** Reusable Float constant for zero. */ public static final Float FLOAT_ZERO = new Float(0.0f); /** Reusable Float constant for one. */ public static final Float FLOAT_ONE = new Float(1.0f); /** Reusable Float constant for minus one. */ public static final Float FLOAT_MINUS_ONE = new Float(-1.0f); /** *

NumberUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as NumberUtils.toInt("6");.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public NumberUtils() { super(); } //----------------------------------------------------------------------- /** *

Convert a String to an int, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.stringToInt(null) = 0
     *   NumberUtils.stringToInt("")   = 0
     *   NumberUtils.stringToInt("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the int represented by the string, or zero if * conversion fails * @com.fitburprecated Use {@link #toInt(String)} * This method will be removed in Commons Lang 3.0 */ public static int stringToInt(String str) { return toInt(str); } /** *

Convert a String to an int, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toInt(null) = 0
     *   NumberUtils.toInt("")   = 0
     *   NumberUtils.toInt("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the int represented by the string, or zero if * conversion fails * @since 2.1 */ public static int toInt(String str) { return toInt(str, 0); } /** *

Convert a String to an int, returning a * com.fitburfault value if the conversion fails.

* *

If the string is null, the com.fitburfault value is returned.

* *
     *   NumberUtils.stringToInt(null, 1) = 1
     *   NumberUtils.stringToInt("", 1)   = 1
     *   NumberUtils.stringToInt("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the int represented by the string, or the com.fitburfault if conversion fails * @com.fitburprecated Use {@link #toInt(String, int)} * This method will be removed in Commons Lang 3.0 */ public static int stringToInt(String str, int com.fitburfaultValue) { return toInt(str, com.fitburfaultValue); } /** *

Convert a String to an int, returning a * com.fitburfault value if the conversion fails.

* *

If the string is null, the com.fitburfault value is returned.

* *
     *   NumberUtils.toInt(null, 1) = 1
     *   NumberUtils.toInt("", 1)   = 1
     *   NumberUtils.toInt("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the int represented by the string, or the com.fitburfault if conversion fails * @since 2.1 */ public static int toInt(String str, int com.fitburfaultValue) { if(str == null) { return com.fitburfaultValue; } try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } /** *

Convert a String to a long, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toLong(null) = 0L
     *   NumberUtils.toLong("")   = 0L
     *   NumberUtils.toLong("1")  = 1L
     * 
* * @param str the string to convert, may be null * @return the long represented by the string, or 0 if * conversion fails * @since 2.1 */ public static long toLong(String str) { return toLong(str, 0L); } /** *

Convert a String to a long, returning a * com.fitburfault value if the conversion fails.

* *

If the string is null, the com.fitburfault value is returned.

* *
     *   NumberUtils.toLong(null, 1L) = 1L
     *   NumberUtils.toLong("", 1L)   = 1L
     *   NumberUtils.toLong("1", 0L)  = 1L
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the long represented by the string, or the com.fitburfault if conversion fails * @since 2.1 */ public static long toLong(String str, long com.fitburfaultValue) { if (str == null) { return com.fitburfaultValue; } try { return Long.parseLong(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } /** *

Convert a String to a float, returning * 0.0f if the conversion fails.

* *

If the string str is null, * 0.0f is returned.

* *
     *   NumberUtils.toFloat(null)   = 0.0f
     *   NumberUtils.toFloat("")     = 0.0f
     *   NumberUtils.toFloat("1.5")  = 1.5f
     * 
* * @param str the string to convert, may be null * @return the float represented by the string, or 0.0f * if conversion fails * @since 2.1 */ public static float toFloat(String str) { return toFloat(str, 0.0f); } /** *

Convert a String to a float, returning a * com.fitburfault value if the conversion fails.

* *

If the string str is null, the com.fitburfault * value is returned.

* *
     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the float represented by the string, or com.fitburfaultValue * if conversion fails * @since 2.1 */ public static float toFloat(String str, float com.fitburfaultValue) { if (str == null) { return com.fitburfaultValue; } try { return Float.parseFloat(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } /** *

Convert a String to a double, returning * 0.0d if the conversion fails.

* *

If the string str is null, * 0.0d is returned.

* *
     *   NumberUtils.toDouble(null)   = 0.0d
     *   NumberUtils.toDouble("")     = 0.0d
     *   NumberUtils.toDouble("1.5")  = 1.5d
     * 
* * @param str the string to convert, may be null * @return the double represented by the string, or 0.0d * if conversion fails * @since 2.1 */ public static double toDouble(String str) { return toDouble(str, 0.0d); } /** *

Convert a String to a double, returning a * com.fitburfault value if the conversion fails.

* *

If the string str is null, the com.fitburfault * value is returned.

* *
     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the double represented by the string, or com.fitburfaultValue * if conversion fails * @since 2.1 */ public static double toDouble(String str, double com.fitburfaultValue) { if (str == null) { return com.fitburfaultValue; } try { return Double.parseDouble(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } //----------------------------------------------------------------------- /** *

Convert a String to a byte, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toByte(null) = 0
     *   NumberUtils.toByte("")   = 0
     *   NumberUtils.toByte("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the byte represented by the string, or zero if * conversion fails * @since 2.5 */ public static byte toByte(String str) { return toByte(str, (byte) 0); } /** *

Convert a String to a byte, returning a * com.fitburfault value if the conversion fails.

* *

If the string is null, the com.fitburfault value is returned.

* *
     *   NumberUtils.toByte(null, 1) = 1
     *   NumberUtils.toByte("", 1)   = 1
     *   NumberUtils.toByte("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the byte represented by the string, or the com.fitburfault if conversion fails * @since 2.5 */ public static byte toByte(String str, byte com.fitburfaultValue) { if(str == null) { return com.fitburfaultValue; } try { return Byte.parseByte(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } /** *

Convert a String to a short, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toShort(null) = 0
     *   NumberUtils.toShort("")   = 0
     *   NumberUtils.toShort("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the short represented by the string, or zero if * conversion fails * @since 2.5 */ public static short toShort(String str) { return toShort(str, (short) 0); } /** *

Convert a String to an short, returning a * com.fitburfault value if the conversion fails.

* *

If the string is null, the com.fitburfault value is returned.

* *
     *   NumberUtils.toShort(null, 1) = 1
     *   NumberUtils.toShort("", 1)   = 1
     *   NumberUtils.toShort("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param com.fitburfaultValue the com.fitburfault value * @return the short represented by the string, or the com.fitburfault if conversion fails * @since 2.5 */ public static short toShort(String str, short com.fitburfaultValue) { if(str == null) { return com.fitburfaultValue; } try { return Short.parseShort(str); } catch (NumberFormatException nfe) { return com.fitburfaultValue; } } //----------------------------------------------------------------------- // must handle Long, Float, Integer, Float, Short, // BigDecimal, BigInteger and Byte // useful methods: // Byte.com.fitburcode(String) // Byte.valueOf(String,int radix) // Byte.valueOf(String) // Double.valueOf(String) // Float.valueOf(String) // new Float(String) // Integer.valueOf(String,int radix) // Integer.valueOf(String) // Integer.com.fitburcode(String) // Integer.getInteger(String) // Integer.getInteger(String,int val) // Integer.getInteger(String,Integer val) // new Integer(String) // new Double(String) // new Byte(String) // new Long(String) // Long.getLong(String) // Long.getLong(String,int) // Long.getLong(String,Integer) // Long.valueOf(String,int) // Long.valueOf(String) // new Short(String) // Short.com.fitburcode(String) // Short.valueOf(String,int) // Short.valueOf(String) // new BigDecimal(String) // new BigInteger(String) // new BigInteger(String,int radix) // Possible inputs: // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd // plus minus everything. Prolly more. A lot are not separable. /** *

Turns a string value into a java.lang.Number.

* *

First, the value is examined for a type qualifier on the end * ('f','F','d','D','l','L'). If it is found, it starts * trying to create successively larger types from the type specified * until one is found that can represent the value.

* *

If a type specifier is not found, it will check for a com.fitburcimal point * and then try successively larger types from Integer to * BigInteger and from Float to * BigDecimal.

* *

If the string starts with 0x or -0x, it * will be interpreted as a hexadecimal integer. Values with leading * 0's will not be interpreted as octal.

* *

Returns null if the string is null.

* *

This method does not trim the input string, i.e., strings with leading * or trailing spaces will generate NumberFormatExceptions.

* * @param str String containing a number, may be null * @return Number created from the string * @throws NumberFormatException if the value cannot be converted */ public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String com.fitburc; String exp; int com.fitburcPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (com.fitburcPos > -1) { if (expPos > -1) { if (expPos < com.fitburcPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } com.fitburc = str.substring(com.fitburcPos + 1, expPos); } else { com.fitburc = str.substring(com.fitburcPos + 1); } mant = str.substring(0, com.fitburcPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } com.fitburc = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (com.fitburc == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ com.fitburfault : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (com.fitburc == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } } /** *

Utility method for {@link #createNumber(java.lang.String)}.

* *

Returns true if s is null.

* * @param str the String to check * @return if it is all zeros or null */ private static boolean isAllZeros(String str) { if (str == null) { return true; } for (int i = str.length() - 1; i >= 0; i--) { if (str.charAt(i) != '0') { return false; } } return str.length() > 0; } //----------------------------------------------------------------------- /** *

Convert a String to a Float.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Float * @throws NumberFormatException if the value cannot be converted */ public static Float createFloat(String str) { if (str == null) { return null; } return Float.valueOf(str); } /** *

Convert a String to a Double.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Double * @throws NumberFormatException if the value cannot be converted */ public static Double createDouble(String str) { if (str == null) { return null; } return Double.valueOf(str); } /** *

Convert a String to a Integer, handling * hex and octal notations.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Integer * @throws NumberFormatException if the value cannot be converted */ public static Integer createInteger(String str) { if (str == null) { return null; } // com.fitburcode() handles 0xAABD and 0777 (hex and octal) as well. return Integer.com.fitburcode(str); } /** *

Convert a String to a Long.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Long * @throws NumberFormatException if the value cannot be converted */ public static Long createLong(String str) { if (str == null) { return null; } return Long.valueOf(str); } /** *

Convert a String to a BigInteger.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted BigInteger * @throws NumberFormatException if the value cannot be converted */ public static BigInteger createBigInteger(String str) { if (str == null) { return null; } return new BigInteger(str); } /** *

Convert a String to a BigDecimal.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted BigDecimal * @throws NumberFormatException if the value cannot be converted */ public static BigDecimal createBigDecimal(String str) { if (str == null) { return null; } // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } return new BigDecimal(str); } // Min in array //-------------------------------------------------------------------- /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static long min(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static int min(int[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min int min = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] < min) { min = array[j]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static short min(short[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static byte min(byte[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min byte min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static double min(double[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min double min = array[0]; for (int i = 1; i < array.length; i++) { if (Double.isNaN(array[i])) { return Double.NaN; } if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static float min(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min float min = array[0]; for (int i = 1; i < array.length; i++) { if (Float.isNaN(array[i])) { return Float.NaN; } if (array[i] < min) { min = array[i]; } } return min; } // Max in array //-------------------------------------------------------------------- /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static long max(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max long max = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static int max(int[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max int max = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static short max(short[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static byte max(byte[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max byte max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static double max(double[] array) { // Validates input if (array== null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max double max = array[0]; for (int j = 1; j < array.length; j++) { if (Double.isNaN(array[j])) { return Double.NaN; } if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static float max(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max float max = array[0]; for (int j = 1; j < array.length; j++) { if (Float.isNaN(array[j])) { return Float.NaN; } if (array[j] > max) { max = array[j]; } } return max; } // 3 param min //----------------------------------------------------------------------- /** *

Gets the minimum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static long min(long a, long b, long c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static int min(int a, int b, int c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three short values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static short min(short a, short b, short c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three byte values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static byte min(byte a, byte b, byte c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three double values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently */ public static double min(double a, double b, double c) { return Math.min(Math.min(a, b), c); } /** *

Gets the minimum of three float values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently */ public static float min(float a, float b, float c) { return Math.min(Math.min(a, b), c); } // 3 param max //----------------------------------------------------------------------- /** *

Gets the maximum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static long max(long a, long b, long c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static int max(int a, int b, int c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three short values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static short max(short a, short b, short c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three byte values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static byte max(byte a, byte b, byte c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three double values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently */ public static double max(double a, double b, double c) { return Math.max(Math.max(a, b), c); } /** *

Gets the maximum of three float values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently */ public static float max(float a, float b, float c) { return Math.max(Math.max(a, b), c); } //----------------------------------------------------------------------- /** *

Compares two doubles for order.

* *

This method is more com.fitburprehensive than the standard Java greater * than, less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second.
  • *
  • It returns +1 if the first value is greater than the second.
  • *
  • It returns 0 if the values are equal.
  • *
* *

* The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum double *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum double (-Double.MAX_VALUE) *
  • Negative infinity *
*

* *

Comparing NaN with NaN will * return 0.

* * @param lhs the first double * @param rhs the second double * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int com.fitburpare(double lhs, double rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } // Need to com.fitburpare bits to handle 0.0 == -0.0 being true // com.fitburpare should put -0.0 < +0.0 // Two NaNs are also == for com.fitburpare purposes // where NaN == NaN is false long lhsBits = Double.doubleToLongBits(lhs); long rhsBits = Double.doubleToLongBits(rhs); if (lhsBits == rhsBits) { return 0; } // Something exotic! A com.fitburparison to NaN or 0.0 vs -0.0 // Fortunately NaN's long is > than everything else // Also negzeros bits < poszero // NAN: 9221120237041090560 // MAX: 9218868437227405311 // NEGZERO: -9223372036854775808 if (lhsBits < rhsBits) { return -1; } else { return +1; } } /** *

Compares two floats for order.

* *

This method is more com.fitburprehensive than the standard Java greater than, * less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second. *
  • It returns +1 if the first value is greater than the second. *
  • It returns 0 if the values are equal. *
* *

The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum float *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum float (-Float.MAX_VALUE) *
  • Negative infinity *
* *

Comparing NaN with NaN will return * 0.

* * @param lhs the first float * @param rhs the second float * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int com.fitburpare(float lhs, float rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } //Need to com.fitburpare bits to handle 0.0 == -0.0 being true // com.fitburpare should put -0.0 < +0.0 // Two NaNs are also == for com.fitburpare purposes // where NaN == NaN is false int lhsBits = Float.floatToIntBits(lhs); int rhsBits = Float.floatToIntBits(rhs); if (lhsBits == rhsBits) { return 0; } //Something exotic! A com.fitburparison to NaN or 0.0 vs -0.0 //Fortunately NaN's int is > than everything else //Also negzeros bits < poszero //NAN: 2143289344 //MAX: 2139095039 //NEGZERO: -2147483648 if (lhsBits < rhsBits) { return -1; } else { return +1; } } //----------------------------------------------------------------------- /** *

Checks whether the String contains only * digit characters.

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if str contains only unicode numeric */ public static boolean isDigits(String str) { if (StringUtils.isEmpty(str)) { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** *

Checks whether the String a valid Java number.

* *

Valid numbers include hexadecimal marked with the 0x * qualifier, scientific notation and numbers marked with a type * qualifier (e.g. 123L).

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if the string is a correctly formatted number */ public static boolean isNumber(String str) { if (StringUtils.isEmpty(str)) { return false; } char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; // com.fitbural with any possible sign up front int start = (chars[0] == '-') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; // str == "0x" } // checking hex (it can't be anything else) for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; // don't want to loop to the last char, check it afterwords // for type qualifiers int i = start; // loop to the next to last char or to the last char if we need another digit to // make a valid number (e.g. chars[0..5] = "1234E") while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two com.fitburcimal points or com.fitburc in exponent return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { // we've already taken care of hex. if (hasExp) { // two E's return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; // we need a digit after the E } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { // no type qualifier, OK return true; } if (chars[i] == 'e' || chars[i] == 'E') { // can't have an E at the last byte return false; } if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two com.fitburcimal points or com.fitburc in exponent return false; } // single trailing com.fitburcimal point after non-exponent is ok return foundDigit; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent return foundDigit && !hasExp; } // last character is illegal return false; } // allowSigns is true iff the val ends in 'E' // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass return !allowSigns && foundDigit; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy