    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3.math;
    018
    019import java.lang.reflect.Array;
    020import java.math.BigDecimal;
    021import java.math.BigInteger;
    022import java.math.RoundingMode;
    023
    024import org.apache.commons.lang3.StringUtils;
    025import org.apache.commons.lang3.Validate;
    026
    027/**
    028 * <p>Provides extra functionality for Java Number classes.</p>
    029 *
    030 * @since 2.0
    031 */
    032public class NumberUtils {
    033
    034    /** Reusable Long constant for zero. */
    035    public static final Long LONG_ZERO = Long.valueOf(0L);
    036    /** Reusable Long constant for one. */
    037    public static final Long LONG_ONE = Long.valueOf(1L);
    038    /** Reusable Long constant for minus one. */
    039    public static final Long LONG_MINUS_ONE = Long.valueOf(-1L);
    040    /** Reusable Integer constant for zero. */
    041    public static final Integer INTEGER_ZERO = Integer.valueOf(0);
    042    /** Reusable Integer constant for one. */
    043    public static final Integer INTEGER_ONE = Integer.valueOf(1);
    044    /** Reusable Integer constant for two */
    045    public static final Integer INTEGER_TWO = Integer.valueOf(2);
    046    /** Reusable Integer constant for minus one. */
    047    public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1);
    048    /** Reusable Short constant for zero. */
    049    public static final Short SHORT_ZERO = Short.valueOf((short) 0);
    050    /** Reusable Short constant for one. */
    051    public static final Short SHORT_ONE = Short.valueOf((short) 1);
    052    /** Reusable Short constant for minus one. */
    053    public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1);
    054    /** Reusable Byte constant for zero. */
    055    public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);
    056    /** Reusable Byte constant for one. */
    057    public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);
    058    /** Reusable Byte constant for minus one. */
    059    public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1);
    060    /** Reusable Double constant for zero. */
    061    public static final Double DOUBLE_ZERO = Double.valueOf(0.0d);
    062    /** Reusable Double constant for one. */
    063    public static final Double DOUBLE_ONE = Double.valueOf(1.0d);
    064    /** Reusable Double constant for minus one. */
    065    public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d);
    066    /** Reusable Float constant for zero. */
    067    public static final Float FLOAT_ZERO = Float.valueOf(0.0f);
    068    /** Reusable Float constant for one. */
    069    public static final Float FLOAT_ONE = Float.valueOf(1.0f);
    070    /** Reusable Float constant for minus one. */
    071    public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);
    072
    073    /**
    074     * {@link Integer#MAX_VALUE} as a {@link Long}.
    075     *
    076     * @since 3.12.0
    077     */
    078    public static final Long LONG_INT_MAX_VALUE = Long.valueOf(Integer.MAX_VALUE);
    079
    080    /**
    081     * {@link Integer#MIN_VALUE} as a {@link Long}.
    082     *
    083     * @since 3.12.0
    084     */
    085    public static final Long LONG_INT_MIN_VALUE = Long.valueOf(Integer.MIN_VALUE);
    086
    087
    088    /**
    089     * <p>{@code NumberUtils} instances should NOT be constructed in standard programming.
    090     * Instead, the class should be used as {@code NumberUtils.toInt("6");}.</p>
    091     *
    092     * <p>This constructor is public to permit tools that require a JavaBean instance
    093     * to operate.</p>
    094     */
    095    public NumberUtils() {
    096    }
    097
    098    //-----------------------------------------------------------------------
    099    /**
    100     * <p>Convert a {@code String} to an {@code int}, returning
    101     * {@code zero} if the conversion fails.</p>
    102     *
    103     * <p>If the string is {@code null}, {@code zero} is returned.</p>
    104     *
    105     * <pre>
    106     *   NumberUtils.toInt(null) = 0
    107     *   NumberUtils.toInt("")   = 0
    108     *   NumberUtils.toInt("1")  = 1
    109     * </pre>
    110     *
    111     * @param str  the string to convert, may be null
    112     * @return the int represented by the string, or {@code zero} if
    113     *  conversion fails
    114     * @since 2.1
    115     */
    116    public static int toInt(final String str) {
    117        return toInt(str, 0);
    118    }
    119
    120    /**
    121     * <p>Convert a {@code String} to an {@code int}, returning a
    122     * default value if the conversion fails.</p>
    123     *
    124     * <p>If the string is {@code null}, the default value is returned.</p>
    125     *
    126     * <pre>
    127     *   NumberUtils.toInt(null, 1) = 1
    128     *   NumberUtils.toInt("", 1)   = 1
    129     *   NumberUtils.toInt("1", 0)  = 1
    130     * </pre>
    131     *
    132     * @param str  the string to convert, may be null
    133     * @param defaultValue  the default value
    134     * @return the int represented by the string, or the default if conversion fails
    135     * @since 2.1
    136     */
    137    public static int toInt(final String str, final int defaultValue) {
    138        if (str == null) {
    139            return defaultValue;
    140        }
    141        try {
    142            return Integer.parseInt(str);
    143        } catch (final NumberFormatException nfe) {
    144            return defaultValue;
    145        }
    146    }
    147
    148    /**
    149     * <p>Convert a {@code String} to a {@code long}, returning
    150     * {@code zero} if the conversion fails.</p>
    151     *
    152     * <p>If the string is {@code null}, {@code zero} is returned.</p>
    153     *
    154     * <pre>
    155     *   NumberUtils.toLong(null) = 0L
    156     *   NumberUtils.toLong("")   = 0L
    157     *   NumberUtils.toLong("1")  = 1L
    158     * </pre>
    159     *
    160     * @param str  the string to convert, may be null
    161     * @return the long represented by the string, or {@code 0} if
    162     *  conversion fails
    163     * @since 2.1
    164     */
    165    public static long toLong(final String str) {
    166        return toLong(str, 0L);
    167    }
    168
    169    /**
    170     * <p>Convert a {@code String} to a {@code long}, returning a
    171     * default value if the conversion fails.</p>
    172     *
    173     * <p>If the string is {@code null}, the default value is returned.</p>
    174     *
    175     * <pre>
    176     *   NumberUtils.toLong(null, 1L) = 1L
    177     *   NumberUtils.toLong("", 1L)   = 1L
    178     *   NumberUtils.toLong("1", 0L)  = 1L
    179     * </pre>
    180     *
    181     * @param str  the string to convert, may be null
    182     * @param defaultValue  the default value
    183     * @return the long represented by the string, or the default if conversion fails
    184     * @since 2.1
    185     */
    186    public static long toLong(final String str, final long defaultValue) {
    187        if (str == null) {
    188            return defaultValue;
    189        }
    190        try {
    191            return Long.parseLong(str);
    192        } catch (final NumberFormatException nfe) {
    193            return defaultValue;
    194        }
    195    }
    196
    197    /**
    198     * <p>Convert a {@code String} to a {@code float}, returning
    199     * {@code 0.0f} if the conversion fails.</p>
    200     *
    201     * <p>If the string {@code str} is {@code null},
    202     * {@code 0.0f} is returned.</p>
    203     *
    204     * <pre>
    205     *   NumberUtils.toFloat(null)   = 0.0f
    206     *   NumberUtils.toFloat("")     = 0.0f
    207     *   NumberUtils.toFloat("1.5")  = 1.5f
    208     * </pre>
    209     *
    210     * @param str the string to convert, may be {@code null}
    211     * @return the float represented by the string, or {@code 0.0f}
    212     *  if conversion fails
    213     * @since 2.1
    214     */
    215    public static float toFloat(final String str) {
    216        return toFloat(str, 0.0f);
    217    }
    218
    219    /**
    220     * <p>Convert a {@code String} to a {@code float}, returning a
    221     * default value if the conversion fails.</p>
    222     *
    223     * <p>If the string {@code str} is {@code null}, the default
    224     * value is returned.</p>
    225     *
    226     * <pre>
    227     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
    228     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
    229     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
    230     * </pre>
    231     *
    232     * @param str the string to convert, may be {@code null}
    233     * @param defaultValue the default value
    234     * @return the float represented by the string, or defaultValue
    235     *  if conversion fails
    236     * @since 2.1
    237     */
    238    public static float toFloat(final String str, final float defaultValue) {
    239      if (str == null) {
    240          return defaultValue;
    241      }
    242      try {
    243          return Float.parseFloat(str);
    244      } catch (final NumberFormatException nfe) {
    245          return defaultValue;
    246      }
    247    }
    248
    249    /**
    250     * <p>Convert a {@code String} to a {@code double}, returning
    251     * {@code 0.0d} if the conversion fails.</p>
    252     *
    253     * <p>If the string {@code str} is {@code null},
    254     * {@code 0.0d} is returned.</p>
    255     *
    256     * <pre>
    257     *   NumberUtils.toDouble(null)   = 0.0d
    258     *   NumberUtils.toDouble("")     = 0.0d
    259     *   NumberUtils.toDouble("1.5")  = 1.5d
    260     * </pre>
    261     *
    262     * @param str the string to convert, may be {@code null}
    263     * @return the double represented by the string, or {@code 0.0d}
    264     *  if conversion fails
    265     * @since 2.1
    266     */
    267    public static double toDouble(final String str) {
    268        return toDouble(str, 0.0d);
    269    }
    270
    271    /**
    272     * <p>Convert a {@code String} to a {@code double}, returning a
    273     * default value if the conversion fails.</p>
    274     *
    275     * <p>If the string {@code str} is {@code null}, the default
    276     * value is returned.</p>
    277     *
    278     * <pre>
    279     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
    280     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
    281     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
    282     * </pre>
    283     *
    284     * @param str the string to convert, may be {@code null}
    285     * @param defaultValue the default value
    286     * @return the double represented by the string, or defaultValue
    287     *  if conversion fails
    288     * @since 2.1
    289     */
    290    public static double toDouble(final String str, final double defaultValue) {
    291      if (str == null) {
    292          return defaultValue;
    293      }
    294      try {
    295          return Double.parseDouble(str);
    296      } catch (final NumberFormatException nfe) {
    297          return defaultValue;
    298      }
    299    }
    300
    301    /**
    302     * <p>Convert a {@code BigDecimal} to a {@code double}.</p>
    303     *
    304     * <p>If the {@code BigDecimal} {@code value} is
    305     * {@code null}, then the specified default value is returned.</p>
    306     *
    307     * <pre>
    308     *   NumberUtils.toDouble(null)                     = 0.0d
    309     *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d)) = 8.5d
    310     * </pre>
    311     *
    312     * @param value the {@code BigDecimal} to convert, may be {@code null}.
    313     * @return the double represented by the {@code BigDecimal} or
    314     *  {@code 0.0d} if the {@code BigDecimal} is {@code null}.
    315     * @since 3.8
    316     */
    317    public static double toDouble(final BigDecimal value) {
    318        return toDouble(value, 0.0d);
    319    }
    320
    321    /**
    322     * <p>Convert a {@code BigDecimal} to a {@code double}.</p>
    323     *
    324     * <p>If the {@code BigDecimal} {@code value} is
    325     * {@code null}, then the specified default value is returned.</p>
    326     *
    327     * <pre>
    328     *   NumberUtils.toDouble(null, 1.1d)                     = 1.1d
    329     *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d), 1.1d) = 8.5d
    330     * </pre>
    331     *
    332     * @param value the {@code BigDecimal} to convert, may be {@code null}.
    333     * @param defaultValue the default value
    334     * @return the double represented by the {@code BigDecimal} or the
    335     *  defaultValue if the {@code BigDecimal} is {@code null}.
    336     * @since 3.8
    337     */
    338    public static double toDouble(final BigDecimal value, final double defaultValue) {
    339        return value == null ? defaultValue : value.doubleValue();
    340    }
    341
    342     //-----------------------------------------------------------------------
    343     /**
    344     * <p>Convert a {@code String} to a {@code byte}, returning
    345     * {@code zero} if the conversion fails.</p>
    346     *
    347     * <p>If the string is {@code null}, {@code zero} is returned.</p>
    348     *
    349     * <pre>
    350     *   NumberUtils.toByte(null) = 0
    351     *   NumberUtils.toByte("")   = 0
    352     *   NumberUtils.toByte("1")  = 1
    353     * </pre>
    354     *
    355     * @param str  the string to convert, may be null
    356     * @return the byte represented by the string, or {@code zero} if
    357     *  conversion fails
    358     * @since 2.5
    359     */
    360    public static byte toByte(final String str) {
    361        return toByte(str, (byte) 0);
    362    }
    363
    364    /**
    365     * <p>Convert a {@code String} to a {@code byte}, returning a
    366     * default value if the conversion fails.</p>
    367     *
    368     * <p>If the string is {@code null}, the default value is returned.</p>
    369     *
    370     * <pre>
    371     *   NumberUtils.toByte(null, 1) = 1
    372     *   NumberUtils.toByte("", 1)   = 1
    373     *   NumberUtils.toByte("1", 0)  = 1
    374     * </pre>
    375     *
    376     * @param str  the string to convert, may be null
    377     * @param defaultValue  the default value
    378     * @return the byte represented by the string, or the default if conversion fails
    379     * @since 2.5
    380     */
    381    public static byte toByte(final String str, final byte defaultValue) {
    382        if (str == null) {
    383            return defaultValue;
    384        }
    385        try {
    386            return Byte.parseByte(str);
    387        } catch (final NumberFormatException nfe) {
    388            return defaultValue;
    389        }
    390    }
    391
    392    /**
    393     * <p>Convert a {@code String} to a {@code short}, returning
    394     * {@code zero} if the conversion fails.</p>
    395     *
    396     * <p>If the string is {@code null}, {@code zero} is returned.</p>
    397     *
    398     * <pre>
    399     *   NumberUtils.toShort(null) = 0
    400     *   NumberUtils.toShort("")   = 0
    401     *   NumberUtils.toShort("1")  = 1
    402     * </pre>
    403     *
    404     * @param str  the string to convert, may be null
    405     * @return the short represented by the string, or {@code zero} if
    406     *  conversion fails
    407     * @since 2.5
    408     */
    409    public static short toShort(final String str) {
    410        return toShort(str, (short) 0);
    411    }
    412
    413    /**
    414     * <p>Convert a {@code String} to an {@code short}, returning a
    415     * default value if the conversion fails.</p>
    416     *
    417     * <p>If the string is {@code null}, the default value is returned.</p>
    418     *
    419     * <pre>
    420     *   NumberUtils.toShort(null, 1) = 1
    421     *   NumberUtils.toShort("", 1)   = 1
    422     *   NumberUtils.toShort("1", 0)  = 1
    423     * </pre>
    424     *
    425     * @param str  the string to convert, may be null
    426     * @param defaultValue  the default value
    427     * @return the short represented by the string, or the default if conversion fails
    428     * @since 2.5
    429     */
    430    public static short toShort(final String str, final short defaultValue) {
    431        if (str == null) {
    432            return defaultValue;
    433        }
    434        try {
    435            return Short.parseShort(str);
    436        } catch (final NumberFormatException nfe) {
    437            return defaultValue;
    438        }
    439    }
    440
    441    /**
    442     * Convert a {@code BigDecimal} to a {@code BigDecimal} with a scale of
    443     * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
    444     * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
    445     *
    446     * <p>Note, the scale of a {@code BigDecimal} is the number of digits to the right of the
    447     * decimal point.</p>
    448     *
    449     * @param value the {@code BigDecimal} to convert, may be null.
    450     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    451     * @since 3.8
    452     */
    453    public static BigDecimal toScaledBigDecimal(final BigDecimal value) {
    454        return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
    455    }
    456
    457    /**
    458     * Convert a {@code BigDecimal} to a {@code BigDecimal} whose scale is the
    459     * specified value with a {@code RoundingMode} applied. If the input {@code value}
    460     * is {@code null}, we simply return {@code BigDecimal.ZERO}.
    461     *
    462     * @param value the {@code BigDecimal} to convert, may be null.
    463     * @param scale the number of digits to the right of the decimal point.
    464     * @param roundingMode a rounding behavior for numerical operations capable of
    465     *  discarding precision.
    466     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    467     * @since 3.8
    468     */
    469    public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, final RoundingMode roundingMode) {
    470        if (value == null) {
    471            return BigDecimal.ZERO;
    472        }
    473        return value.setScale(
    474            scale,
    475            (roundingMode == null) ? RoundingMode.HALF_EVEN : roundingMode
    476        );
    477    }
    478
    479    /**
    480     * Convert a {@code Float} to a {@code BigDecimal} with a scale of
    481     * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
    482     * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
    483     *
    484     * <p>Note, the scale of a {@code BigDecimal} is the number of digits to the right of the
    485     * decimal point.</p>
    486     *
    487     * @param value the {@code Float} to convert, may be null.
    488     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    489     * @since 3.8
    490     */
    491    public static BigDecimal toScaledBigDecimal(final Float value) {
    492        return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
    493    }
    494
    495    /**
    496     * Convert a {@code Float} to a {@code BigDecimal} whose scale is the
    497     * specified value with a {@code RoundingMode} applied. If the input {@code value}
    498     * is {@code null}, we simply return {@code BigDecimal.ZERO}.
    499     *
    500     * @param value the {@code Float} to convert, may be null.
    501     * @param scale the number of digits to the right of the decimal point.
    502     * @param roundingMode a rounding behavior for numerical operations capable of
    503     *  discarding precision.
    504     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    505     * @since 3.8
    506     */
    507    public static BigDecimal toScaledBigDecimal(final Float value, final int scale, final RoundingMode roundingMode) {
    508        if (value == null) {
    509            return BigDecimal.ZERO;
    510        }
    511        return toScaledBigDecimal(
    512            BigDecimal.valueOf(value),
    513            scale,
    514            roundingMode
    515        );
    516    }
    517
    518    /**
    519     * Convert a {@code Double} to a {@code BigDecimal} with a scale of
    520     * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
    521     * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
    522     *
    523     * <p>Note, the scale of a {@code BigDecimal} is the number of digits to the right of the
    524     * decimal point.</p>
    525     *
    526     * @param value the {@code Double} to convert, may be null.
    527     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    528     * @since 3.8
    529     */
    530    public static BigDecimal toScaledBigDecimal(final Double value) {
    531        return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
    532    }
    533
    534    /**
    535     * Convert a {@code Double} to a {@code BigDecimal} whose scale is the
    536     * specified value with a {@code RoundingMode} applied. If the input {@code value}
    537     * is {@code null}, we simply return {@code BigDecimal.ZERO}.
    538     *
    539     * @param value the {@code Double} to convert, may be null.
    540     * @param scale the number of digits to the right of the decimal point.
    541     * @param roundingMode a rounding behavior for numerical operations capable of
    542     *  discarding precision.
    543     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    544     * @since 3.8
    545     */
    546    public static BigDecimal toScaledBigDecimal(final Double value, final int scale, final RoundingMode roundingMode) {
    547        if (value == null) {
    548            return BigDecimal.ZERO;
    549        }
    550        return toScaledBigDecimal(
    551            BigDecimal.valueOf(value),
    552            scale,
    553            roundingMode
    554        );
    555    }
    556
    557    /**
    558     * Convert a {@code String} to a {@code BigDecimal} with a scale of
    559     * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
    560     * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
    561     *
    562     * <p>Note, the scale of a {@code BigDecimal} is the number of digits to the right of the
    563     * decimal point.</p>
    564     *
    565     * @param value the {@code String} to convert, may be null.
    566     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    567     * @since 3.8
    568     */
    569    public static BigDecimal toScaledBigDecimal(final String value) {
    570        return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
    571    }
    572
    573    /**
    574     * Convert a {@code String} to a {@code BigDecimal} whose scale is the
    575     * specified value with a {@code RoundingMode} applied. If the input {@code value}
    576     * is {@code null}, we simply return {@code BigDecimal.ZERO}.
    577     *
    578     * @param value the {@code String} to convert, may be null.
    579     * @param scale the number of digits to the right of the decimal point.
    580     * @param roundingMode a rounding behavior for numerical operations capable of
    581     *  discarding precision.
    582     * @return the scaled, with appropriate rounding, {@code BigDecimal}.
    583     * @since 3.8
    584     */
    585    public static BigDecimal toScaledBigDecimal(final String value, final int scale, final RoundingMode roundingMode) {
    586        if (value == null) {
    587            return BigDecimal.ZERO;
    588        }
    589        return toScaledBigDecimal(
    590            createBigDecimal(value),
    591            scale,
    592            roundingMode
    593        );
    594    }
    595
    596    //-----------------------------------------------------------------------
    597    // must handle Long, Float, Integer, Float, Short,
    598    //                  BigDecimal, BigInteger and Byte
    599    // useful methods:
    600    // Byte.decode(String)
    601    // Byte.valueOf(String, int radix)
    602    // Byte.valueOf(String)
    603    // Double.valueOf(String)
    604    // Float.valueOf(String)
    605    // Float.valueOf(String)
    606    // Integer.valueOf(String, int radix)
    607    // Integer.valueOf(String)
    608    // Integer.decode(String)
    609    // Integer.getInteger(String)
    610    // Integer.getInteger(String, int val)
    611    // Integer.getInteger(String, Integer val)
    612    // Integer.valueOf(String)
    613    // Double.valueOf(String)
    614    // new Byte(String)
    615    // Long.valueOf(String)
    616    // Long.getLong(String)
    617    // Long.getLong(String, int)
    618    // Long.getLong(String, Integer)
    619    // Long.valueOf(String, int)
    620    // Long.valueOf(String)
    621    // Short.valueOf(String)
    622    // Short.decode(String)
    623    // Short.valueOf(String, int)
    624    // Short.valueOf(String)
    625    // new BigDecimal(String)
    626    // new BigInteger(String)
    627    // new BigInteger(String, int radix)
    628    // Possible inputs:
    629    // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
    630    // plus minus everything. Prolly more. A lot are not separable.
    631
    632    /**
    633     * <p>Turns a string value into a java.lang.Number.</p>
    634     *
    635     * <p>If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it
    636     * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the
    637     * prefix is more than 8 - or BigInteger if there are more than 16 digits.
    638     * </p>
    639     * <p>Then, the value is examined for a type qualifier on the end, i.e. one of
    640     * {@code 'f', 'F', 'd', 'D', 'l', 'L'}.  If it is found, it starts
    641     * trying to create successively larger types from the type specified
    642     * until one is found that can represent the value.</p>
    643     *
    644     * <p>If a type specifier is not found, it will check for a decimal point
    645     * and then try successively larger types from {@code Integer} to
    646     * {@code BigInteger} and from {@code Float} to
    647    * {@code BigDecimal}.</p>
    648    *
    649     * <p>
    650     * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
    651     * be Integer, Long or BigDecimal as appropriate.
    652     * </p>
    653     *
    654     * <p>Returns {@code null} if the string is {@code null}.</p>
    655     *
    656     * <p>This method does not trim the input string, i.e., strings with leading
    657     * or trailing spaces will generate NumberFormatExceptions.</p>
    658     *
    659     * @param str  String containing a number, may be null
    660     * @return Number created from the string (or null if the input is null)
    661     * @throws NumberFormatException if the value cannot be converted
    662     */
    663    public static Number createNumber(final String str) {
    664        if (str == null) {
    665            return null;
    666        }
    667        if (StringUtils.isBlank(str)) {
    668            throw new NumberFormatException("A blank string is not a valid number");
    669        }
    670        // Need to deal with all possible hex prefixes here
    671        final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"};
    672        final int length = str.length();
    673        int pfxLen = 0;
    674        for (final String pfx : hex_prefixes) {
    675            if (str.startsWith(pfx)) {
    676                pfxLen += pfx.length();
    677                break;
    678            }
    679        }
    680        if (pfxLen > 0) { // we have a hex number
    681            char firstSigDigit = 0; // strip leading zeroes
    682            for (int i = pfxLen; i < length; i++) {
    683                firstSigDigit = str.charAt(i);
    684                if (firstSigDigit == '0') { // count leading zeroes
    685                    pfxLen++;
    686                } else {
    687                    break;
    688                }
    689            }
    690            final int hexDigits = length - pfxLen;
    691            if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long
    692                return createBigInteger(str);
    693            }
    694            if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int
    695                return createLong(str);
    696            }
    697            return createInteger(str);
    698        }
    699        final char lastChar = str.charAt(length - 1);
    700        final String mant;
    701        final String dec;
    702        final String exp;
    703        final int decPos = str.indexOf('.');
    704        final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
    705        // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
    706        // and the parsing which will detect if e or E appear in a number due to using the wrong offset
    707
    708        if (decPos > -1) { // there is a decimal point
    709            if (expPos > -1) { // there is an exponent
    710                if (expPos < decPos || expPos > length) { // prevents double exponent causing IOOBE
    711                    throw new NumberFormatException(str + " is not a valid number.");
    712                }
    713                dec = str.substring(decPos + 1, expPos);
    714            } else {
    715                dec = str.substring(decPos + 1);
    716            }
    717            mant = getMantissa(str, decPos);
    718        } else {
    719            if (expPos > -1) {
    720                if (expPos > length) { // prevents double exponent causing IOOBE
    721                    throw new NumberFormatException(str + " is not a valid number.");
    722                }
    723                mant = getMantissa(str, expPos);
    724            } else {
    725                mant = getMantissa(str);
    726            }
    727            dec = null;
    728        }
    729        if (!Character.isDigit(lastChar) && lastChar != '.') {
    730            if (expPos > -1 && expPos < length - 1) {
    731                exp = str.substring(expPos + 1, length - 1);
    732            } else {
    733                exp = null;
    734            }
    735            //Requesting a specific type..
    736            final String numeric = str.substring(0, length - 1);
    737            final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
    738            switch (lastChar) {
    739                case 'l' :
    740                case 'L' :
    741                    if (dec == null
    742                        && exp == null
    743                        && (!numeric.isEmpty() && numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
    744                        try {
    745                            return createLong(numeric);
    746                        } catch (final NumberFormatException nfe) { // NOPMD
    747                            // Too big for a long
    748                        }
    749                        return createBigInteger(numeric);
    750
    751                    }
    752                    throw new NumberFormatException(str + " is not a valid number.");
    753                case 'f' :
    754                case 'F' :
    755                    try {
    756                        final Float f = createFloat(str);
    757                        if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) {
    758                            //If it's too big for a float or the float value = 0 and the string
    759                            //has non-zeros in it, then float does not have the precision we want
    760                            return f;
    761                        }
    762
    763                    } catch (final NumberFormatException nfe) { // NOPMD
    764                        // ignore the bad number
    765                    }
    766                    //$FALL-THROUGH$
    767                case 'd' :
    768                case 'D' :
    769                    try {
    770                        final Double d = createDouble(str);
    771                        if (!(d.isInfinite() || d.doubleValue() == 0.0D && !allZeros)) {
    772                            return d;
    773                        }
    774                    } catch (final NumberFormatException nfe) { // NOPMD
    775                        // ignore the bad number
    776                    }
    777                    try {
    778                        return createBigDecimal(numeric);
    779                    } catch (final NumberFormatException e) { // NOPMD
    780                        // ignore the bad number
    781                    }
    782                    //$FALL-THROUGH$
    783                default :
    784                    throw new NumberFormatException(str + " is not a valid number.");
    785
    786            }
    787        }
    788        //User doesn't have a preference on the return type, so let's start
    789        //small and go from there...
    790        if (expPos > -1 && expPos < length - 1) {
    791            exp = str.substring(expPos + 1);
    792        } else {
    793            exp = null;
    794        }
    795        if (dec == null && exp == null) { // no decimal point and no exponent
    796            //Must be an Integer, Long, Biginteger
    797            try {
    798                return createInteger(str);
    799            } catch (final NumberFormatException nfe) { // NOPMD
    800                // ignore the bad number
    801            }
    802            try {
    803                return createLong(str);
    804            } catch (final NumberFormatException nfe) { // NOPMD
    805                // ignore the bad number
    806            }
    807            return createBigInteger(str);
    808        }
    809
    810        //Must be a Float, Double, BigDecimal
    811        final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
    812        try {
    813            final Float f = createFloat(str);
    814            final Double d = createDouble(str);
    815            if (!f.isInfinite()
    816                    && !(f.floatValue() == 0.0F && !allZeros)
    817                    && f.toString().equals(d.toString())) {
    818                return f;
    819            }
    820            if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) {
    821                final BigDecimal b = createBigDecimal(str);
    822                if (b.compareTo(BigDecimal.valueOf(d.doubleValue())) == 0) {
    823                    return d;
    824                }
    825                return b;
    826            }
    827        } catch (final NumberFormatException nfe) { // NOPMD
    828            // ignore the bad number
    829        }
    830        return createBigDecimal(str);
    831    }
    832
    833    /**
    834     * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
    835     *
    836     * <p>Returns mantissa of the given number.</p>
    837     *
    838     * @param str the string representation of the number
    839     * @return mantissa of the given number
    840     */
    841    private static String getMantissa(final String str) {
    842        return getMantissa(str, str.length());
    843    }
    844
    845    /**
    846     * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
    847     *
    848     * <p>Returns mantissa of the given number.</p>
    849     *
    850     * @param str the string representation of the number
    851     * @param stopPos the position of the exponent or decimal point
    852     * @return mantissa of the given number
    853     */
    854    private static String getMantissa(final String str, final int stopPos) {
    855        final char firstChar = str.charAt(0);
    856        final boolean hasSign = firstChar == '-' || firstChar == '+';
    857
    858        return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos);
    859    }
    860
    861    /**
    862     * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
    863     *
    864     * <p>Returns {@code true} if s is {@code null}.</p>
    865     *
    866     * @param str  the String to check
    867     * @return if it is all zeros or {@code null}
    868     */
    869    private static boolean isAllZeros(final String str) {
    870        if (str == null) {
    871            return true;
    872        }
    873        for (int i = str.length() - 1; i >= 0; i--) {
    874            if (str.charAt(i) != '0') {
    875                return false;
    876            }
    877        }
    878        return !str.isEmpty();
    879    }
    880
    881    //-----------------------------------------------------------------------
    882    /**
    883     * <p>Convert a {@code String} to a {@code Float}.</p>
    884     *
    885     * <p>Returns {@code null} if the string is {@code null}.</p>
    886     *
    887     * @param str  a {@code String} to convert, may be null
    888     * @return converted {@code Float} (or null if the input is null)
    889     * @throws NumberFormatException if the value cannot be converted
    890     */
    891    public static Float createFloat(final String str) {
    892        if (str == null) {
    893            return null;
    894        }
    895        return Float.valueOf(str);
    896    }
    897
    898    /**
    899     * <p>Convert a {@code String} to a {@code Double}.</p>
    900     *
    901     * <p>Returns {@code null} if the string is {@code null}.</p>
    902     *
    903     * @param str  a {@code String} to convert, may be null
    904     * @return converted {@code Double} (or null if the input is null)
    905     * @throws NumberFormatException if the value cannot be converted
    906     */
    907    public static Double createDouble(final String str) {
    908        if (str == null) {
    909            return null;
    910        }
    911        return Double.valueOf(str);
    912    }
    913
    914    /**
    915     * <p>Convert a {@code String} to a {@code Integer}, handling
    916     * hex (0xhhhh) and octal (0dddd) notations.
    917     * N.B. a leading zero means octal; spaces are not trimmed.</p>
    918     *
    919     * <p>Returns {@code null} if the string is {@code null}.</p>
    920     *
    921     * @param str  a {@code String} to convert, may be null
    922     * @return converted {@code Integer} (or null if the input is null)
    923     * @throws NumberFormatException if the value cannot be converted
    924     */
    925    public static Integer createInteger(final String str) {
    926        if (str == null) {
    927            return null;
    928        }
    929        // decode() handles 0xAABD and 0777 (hex and octal) as well.
    930        return Integer.decode(str);
    931    }
    932
    933    /**
    934     * <p>Convert a {@code String} to a {@code Long};
    935     * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations.
    936     * N.B. a leading zero means octal; spaces are not trimmed.</p>
    937     *
    938     * <p>Returns {@code null} if the string is {@code null}.</p>
    939     *
    940     * @param str  a {@code String} to convert, may be null
    941     * @return converted {@code Long} (or null if the input is null)
    942     * @throws NumberFormatException if the value cannot be converted
    943     */
    944    public static Long createLong(final String str) {
    945        if (str == null) {
    946            return null;
    947        }
    948        return Long.decode(str);
    949    }
    950
    951    /**
    952     * <p>Convert a {@code String} to a {@code BigInteger};
    953     * since 3.2 it handles hex (0x or #) and octal (0) notations.</p>
    954     *
    955     * <p>Returns {@code null} if the string is {@code null}.</p>
    956     *
    957     * @param str  a {@code String} to convert, may be null
    958     * @return converted {@code BigInteger} (or null if the input is null)
    959     * @throws NumberFormatException if the value cannot be converted
    960     */
    961    public static BigInteger createBigInteger(final String str) {
    962        if (str == null) {
    963            return null;
    964        }
    965        int pos = 0; // offset within string
    966        int radix = 10;
    967        boolean negate = false; // need to negate later?
    968        if (str.startsWith("-")) {
    969            negate = true;
    970            pos = 1;
    971        }
    972        if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex
    973            radix = 16;
    974            pos += 2;
    975        } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
    976            radix = 16;
    977            pos++;
    978        } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
    979            radix = 8;
    980            pos++;
    981        } // default is to treat as decimal
    982
    983        final BigInteger value = new BigInteger(str.substring(pos), radix);
    984        return negate ? value.negate() : value;
    985    }
    986
    987    /**
    988     * <p>Convert a {@code String} to a {@code BigDecimal}.</p>
    989     *
    990     * <p>Returns {@code null} if the string is {@code null}.</p>
    991     *
    992     * @param str  a {@code String} to convert, may be null
    993     * @return converted {@code BigDecimal} (or null if the input is null)
    994     * @throws NumberFormatException if the value cannot be converted
    995     */
    996    public static BigDecimal createBigDecimal(final String str) {
    997        if (str == null) {
    998            return null;
    999        }
    1000        // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
    1001        if (StringUtils.isBlank(str)) {
    1002            throw new NumberFormatException("A blank string is not a valid number");
    1003        }
    1004        return new BigDecimal(str);
    1005    }
    1006
    1007    // Min in array
    1008    //--------------------------------------------------------------------
    1009    /**
    1010     * <p>Returns the minimum value in an array.</p>
    1011     *
    1012     * @param array  an array, must not be null or empty
    1013     * @return the minimum value in the array
    1014     * @throws IllegalArgumentException if {@code array} is {@code null}
    1015     * @throws IllegalArgumentException if {@code array} is empty
    1016     * @since 3.4 Changed signature from min(long[]) to min(long...)
    1017     */
    1018    public static long min(final long... array) {
    1019        // Validates input
    1020        validateArray(array);
    1021
    1022        // Finds and returns min
    1023        long min = array[0];
    1024        for (int i = 1; i < array.length; i++) {
    1025            if (array[i] < min) {
    1026                min = array[i];
    1027            }
    1028        }
    1029
    1030        return min;
    1031    }
    1032
    1033    /**
    1034     * <p>Returns the minimum value in an array.</p>
    1035     *
    1036     * @param array  an array, must not be null or empty
    1037     * @return the minimum value in the array
    1038     * @throws IllegalArgumentException if {@code array} is {@code null}
    1039     * @throws IllegalArgumentException if {@code array} is empty
    1040     * @since 3.4 Changed signature from min(int[]) to min(int...)
    1041     */
    1042    public static int min(final int... array) {
    1043        // Validates input
    1044        validateArray(array);
    1045
    1046        // Finds and returns min
    1047        int min = array[0];
    1048        for (int j = 1; j < array.length; j++) {
    1049            if (array[j] < min) {
    1050                min = array[j];
    1051            }
    1052        }
    1053
    1054        return min;
    1055    }
    1056
    1057    /**
    1058     * <p>Returns the minimum value in an array.</p>
    1059     *
    1060     * @param array  an array, must not be null or empty
    1061     * @return the minimum value in the array
    1062     * @throws IllegalArgumentException if {@code array} is {@code null}
    1063     * @throws IllegalArgumentException if {@code array} is empty
    1064     * @since 3.4 Changed signature from min(short[]) to min(short...)
    1065     */
    1066    public static short min(final short... array) {
    1067        // Validates input
    1068        validateArray(array);
    1069
    1070        // Finds and returns min
    1071        short min = array[0];
    1072        for (int i = 1; i < array.length; i++) {
    1073            if (array[i] < min) {
    1074                min = array[i];
    1075            }
    1076        }
    1077
    1078        return min;
    1079    }
    1080
    1081    /**
    1082     * <p>Returns the minimum value in an array.</p>
    1083     *
    1084     * @param array  an array, must not be null or empty
    1085     * @return the minimum value in the array
    1086     * @throws IllegalArgumentException if {@code array} is {@code null}
    1087     * @throws IllegalArgumentException if {@code array} is empty
    1088     * @since 3.4 Changed signature from min(byte[]) to min(byte...)
    1089     */
    1090    public static byte min(final byte... array) {
    1091        // Validates input
    1092        validateArray(array);
    1093
    1094        // Finds and returns min
    1095        byte min = array[0];
    1096        for (int i = 1; i < array.length; i++) {
    1097            if (array[i] < min) {
    1098                min = array[i];
    1099            }
    1100        }
    1101
    1102        return min;
    1103    }
    1104
    1105     /**
    1106     * <p>Returns the minimum value in an array.</p>
    1107     *
    1108     * @param array  an array, must not be null or empty
    1109     * @return the minimum value in the array
    1110     * @throws IllegalArgumentException if {@code array} is {@code null}
    1111     * @throws IllegalArgumentException if {@code array} is empty
    1112     * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
    1113     * @since 3.4 Changed signature from min(double[]) to min(double...)
    1114     */
    1115    public static double min(final double... array) {
    1116        // Validates input
    1117        validateArray(array);
    1118
    1119        // Finds and returns min
    1120        double min = array[0];
    1121        for (int i = 1; i < array.length; i++) {
    1122            if (Double.isNaN(array[i])) {
    1123                return Double.NaN;
    1124            }
    1125            if (array[i] < min) {
    1126                min = array[i];
    1127            }
    1128        }
    1129
    1130        return min;
    1131    }
    1132
    1133    /**
    1134     * <p>Returns the minimum value in an array.</p>
    1135     *
    1136     * @param array  an array, must not be null or empty
    1137     * @return the minimum value in the array
    1138     * @throws IllegalArgumentException if {@code array} is {@code null}
    1139     * @throws IllegalArgumentException if {@code array} is empty
    1140     * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
    1141     * @since 3.4 Changed signature from min(float[]) to min(float...)
    1142     */
    1143    public static float min(final float... array) {
    1144        // Validates input
    1145        validateArray(array);
    1146
    1147        // Finds and returns min
    1148        float min = array[0];
    1149        for (int i = 1; i < array.length; i++) {
    1150            if (Float.isNaN(array[i])) {
    1151                return Float.NaN;
    1152            }
    1153            if (array[i] < min) {
    1154                min = array[i];
    1155            }
    1156        }
    1157
    1158        return min;
    1159    }
    1160
    1161    // Max in array
    1162    //--------------------------------------------------------------------
    1163    /**
    1164     * <p>Returns the maximum value in an array.</p>
    1165     *
    1166     * @param array  an array, must not be null or empty
    1167     * @return the maximum value in the array
    1168     * @throws IllegalArgumentException if {@code array} is {@code null}
    1169     * @throws IllegalArgumentException if {@code array} is empty
    1170     * @since 3.4 Changed signature from max(long[]) to max(long...)
    1171     */
    1172    public static long max(final long... array) {
    1173        // Validates input
    1174        validateArray(array);
    1175
    1176        // Finds and returns max
    1177        long max = array[0];
    1178        for (int j = 1; j < array.length; j++) {
    1179            if (array[j] > max) {
    1180                max = array[j];
    1181            }
    1182        }
    1183
    1184        return max;
    1185    }
    1186
    1187    /**
    1188     * <p>Returns the maximum value in an array.</p>
    1189     *
    1190     * @param array  an array, must not be null or empty
    1191     * @return the maximum value in the array
    1192     * @throws IllegalArgumentException if {@code array} is {@code null}
    1193     * @throws IllegalArgumentException if {@code array} is empty
    1194     * @since 3.4 Changed signature from max(int[]) to max(int...)
    1195     */
    1196    public static int max(final int... array) {
    1197        // Validates input
    1198        validateArray(array);
    1199
    1200        // Finds and returns max
    1201        int max = array[0];
    1202        for (int j = 1; j < array.length; j++) {
    1203            if (array[j] > max) {
    1204                max = array[j];
    1205            }
    1206        }
    1207
    1208        return max;
    1209    }
    1210
    1211    /**
    1212     * <p>Returns the maximum value in an array.</p>
    1213     *
    1214     * @param array  an array, must not be null or empty
    1215     * @return the maximum value in the array
    1216     * @throws IllegalArgumentException if {@code array} is {@code null}
    1217     * @throws IllegalArgumentException if {@code array} is empty
    1218     * @since 3.4 Changed signature from max(short[]) to max(short...)
    1219     */
    1220    public static short max(final short... array) {
    1221        // Validates input
    1222        validateArray(array);
    1223
    1224        // Finds and returns max
    1225        short max = array[0];
    1226        for (int i = 1; i < array.length; i++) {
    1227            if (array[i] > max) {
    1228                max = array[i];
    1229            }
    1230        }
    1231
    1232        return max;
    1233    }
    1234
    1235    /**
    1236     * <p>Returns the maximum value in an array.</p>
    1237     *
    1238     * @param array  an array, must not be null or empty
    1239     * @return the maximum value in the array
    1240     * @throws IllegalArgumentException if {@code array} is {@code null}
    1241     * @throws IllegalArgumentException if {@code array} is empty
    1242     * @since 3.4 Changed signature from max(byte[]) to max(byte...)
    1243     */
    1244    public static byte max(final byte... array) {
    1245        // Validates input
    1246        validateArray(array);
    1247
    1248        // Finds and returns max
    1249        byte max = array[0];
    1250        for (int i = 1; i < array.length; i++) {
    1251            if (array[i] > max) {
    1252                max = array[i];
    1253            }
    1254        }
    1255
    1256        return max;
    1257    }
    1258
    1259    /**
    1260     * <p>Returns the maximum value in an array.</p>
    1261     *
    1262     * @param array  an array, must not be null or empty
    1263     * @return the maximum value in the array
    1264     * @throws IllegalArgumentException if {@code array} is {@code null}
    1265     * @throws IllegalArgumentException if {@code array} is empty
    1266     * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
    1267     * @since 3.4 Changed signature from max(double[]) to max(double...)
    1268     */
    1269    public static double max(final double... array) {
    1270        // Validates input
    1271        validateArray(array);
    1272
    1273        // Finds and returns max
    1274        double max = array[0];
    1275        for (int j = 1; j < array.length; j++) {
    1276            if (Double.isNaN(array[j])) {
    1277                return Double.NaN;
    1278            }
    1279            if (array[j] > max) {
    1280                max = array[j];
    1281            }
    1282        }
    1283
    1284        return max;
    1285    }
    1286
    1287    /**
    1288     * <p>Returns the maximum value in an array.</p>
    1289     *
    1290     * @param array  an array, must not be null or empty
    1291     * @return the maximum value in the array
    1292     * @throws IllegalArgumentException if {@code array} is {@code null}
    1293     * @throws IllegalArgumentException if {@code array} is empty
    1294     * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
    1295     * @since 3.4 Changed signature from max(float[]) to max(float...)
    1296     */
    1297    public static float max(final float... array) {
    1298        // Validates input
    1299        validateArray(array);
    1300
    1301        // Finds and returns max
    1302        float max = array[0];
    1303        for (int j = 1; j < array.length; j++) {
    1304            if (Float.isNaN(array[j])) {
    1305                return Float.NaN;
    1306            }
    1307            if (array[j] > max) {
    1308                max = array[j];
    1309            }
    1310        }
    1311
    1312        return max;
    1313    }
    1314
    1315    /**
    1316     * Checks if the specified array is neither null nor empty.
    1317     *
    1318     * @param array  the array to check
    1319     * @throws IllegalArgumentException if {@code array} is either {@code null} or empty
    1320     */
    1321    private static void validateArray(final Object array) {
    1322        Validate.notNull(array, "array");
    1323        Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");
    1324    }
    1325
    1326    // 3 param min
    1327    //-----------------------------------------------------------------------
    1328    /**
    1329     * <p>Gets the minimum of three {@code long} values.</p>
    1330     *
    1331     * @param a  value 1
    1332     * @param b  value 2
    1333     * @param c  value 3
    1334     * @return  the smallest of the values
    1335     */
    1336    public static long min(long a, final long b, final long c) {
    1337        if (b < a) {
    1338            a = b;
    1339        }
    1340        if (c < a) {
    1341            a = c;
    1342        }
    1343        return a;
    1344    }
    1345
    1346    /**
    1347     * <p>Gets the minimum of three {@code int} values.</p>
    1348     *
    1349     * @param a  value 1
    1350     * @param b  value 2
    1351     * @param c  value 3
    1352     * @return  the smallest of the values
    1353     */
    1354    public static int min(int a, final int b, final int c) {
    1355        if (b < a) {
    1356            a = b;
    1357        }
    1358        if (c < a) {
    1359            a = c;
    1360        }
    1361        return a;
    1362    }
    1363
    1364    /**
    1365     * <p>Gets the minimum of three {@code short} values.</p>
    1366     *
    1367     * @param a  value 1
    1368     * @param b  value 2
    1369     * @param c  value 3
    1370     * @return  the smallest of the values
    1371     */
    1372    public static short min(short a, final short b, final short c) {
    1373        if (b < a) {
    1374            a = b;
    1375        }
    1376        if (c < a) {
    1377            a = c;
    1378        }
    1379        return a;
    1380    }
    1381
    1382    /**
    1383     * <p>Gets the minimum of three {@code byte} values.</p>
    1384     *
    1385     * @param a  value 1
    1386     * @param b  value 2
    1387     * @param c  value 3
    1388     * @return  the smallest of the values
    1389     */
    1390    public static byte min(byte a, final byte b, final byte c) {
    1391        if (b < a) {
    1392            a = b;
    1393        }
    1394        if (c < a) {
    1395            a = c;
    1396        }
    1397        return a;
    1398    }
    1399
    1400    /**
    1401     * <p>Gets the minimum of three {@code double} values.</p>
    1402     *
    1403     * <p>If any value is {@code NaN}, {@code NaN} is
    1404     * returned. Infinity is handled.</p>
    1405     *
    1406     * @param a  value 1
    1407     * @param b  value 2
    1408     * @param c  value 3
    1409     * @return  the smallest of the values
    1410     * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently
    1411     */
    1412    public static double min(final double a, final double b, final double c) {
    1413        return Math.min(Math.min(a, b), c);
    1414    }
    1415
    1416    /**
    1417     * <p>Gets the minimum of three {@code float} values.</p>
    1418     *
    1419     * <p>If any value is {@code NaN}, {@code NaN} is
    1420     * returned. Infinity is handled.</p>
    1421     *
    1422     * @param a  value 1
    1423     * @param b  value 2
    1424     * @param c  value 3
    1425     * @return  the smallest of the values
    1426     * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently
    1427     */
    1428    public static float min(final float a, final float b, final float c) {
    1429        return Math.min(Math.min(a, b), c);
    1430    }
    1431
    1432    // 3 param max
    1433    //-----------------------------------------------------------------------
    1434    /**
    1435     * <p>Gets the maximum of three {@code long} values.</p>
    1436     *
    1437     * @param a  value 1
    1438     * @param b  value 2
    1439     * @param c  value 3
    1440     * @return  the largest of the values
    1441     */
    1442    public static long max(long a, final long b, final long c) {
    1443        if (b > a) {
    1444            a = b;
    1445        }
    1446        if (c > a) {
    1447            a = c;
    1448        }
    1449        return a;
    1450    }
    1451
    1452    /**
    1453     * <p>Gets the maximum of three {@code int} values.</p>
    1454     *
    1455     * @param a  value 1
    1456     * @param b  value 2
    1457     * @param c  value 3
    1458     * @return  the largest of the values
    1459     */
    1460    public static int max(int a, final int b, final int c) {
    1461        if (b > a) {
    1462            a = b;
    1463        }
    1464        if (c > a) {
    1465            a = c;
    1466        }
    1467        return a;
    1468    }
    1469
    1470    /**
    1471     * <p>Gets the maximum of three {@code short} values.</p>
    1472     *
    1473     * @param a  value 1
    1474     * @param b  value 2
    1475     * @param c  value 3
    1476     * @return  the largest of the values
    1477     */
    1478    public static short max(short a, final short b, final short c) {
    1479        if (b > a) {
    1480            a = b;
    1481        }
    1482        if (c > a) {
    1483            a = c;
    1484        }
    1485        return a;
    1486    }
    1487
    1488    /**
    1489     * <p>Gets the maximum of three {@code byte} values.</p>
    1490     *
    1491     * @param a  value 1
    1492     * @param b  value 2
    1493     * @param c  value 3
    1494     * @return  the largest of the values
    1495     */
    1496    public static byte max(byte a, final byte b, final byte c) {
    1497        if (b > a) {
    1498            a = b;
    1499        }
    1500        if (c > a) {
    1501            a = c;
    1502        }
    1503        return a;
    1504    }
    1505
    1506    /**
    1507     * <p>Gets the maximum of three {@code double} values.</p>
    1508     *
    1509     * <p>If any value is {@code NaN}, {@code NaN} is
    1510     * returned. Infinity is handled.</p>
    1511     *
    1512     * @param a  value 1
    1513     * @param b  value 2
    1514     * @param c  value 3
    1515     * @return  the largest of the values
    1516     * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently
    1517     */
    1518    public static double max(final double a, final double b, final double c) {
    1519        return Math.max(Math.max(a, b), c);
    1520    }
    1521
    1522    /**
    1523     * <p>Gets the maximum of three {@code float} values.</p>
    1524     *
    1525     * <p>If any value is {@code NaN}, {@code NaN} is
    1526     * returned. Infinity is handled.</p>
    1527     *
    1528     * @param a  value 1
    1529     * @param b  value 2
    1530     * @param c  value 3
    1531     * @return  the largest of the values
    1532     * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently
    1533     */
    1534    public static float max(final float a, final float b, final float c) {
    1535        return Math.max(Math.max(a, b), c);
    1536    }
    1537
    1538    //-----------------------------------------------------------------------
    1539    /**
    1540     * <p>Checks whether the {@code String} contains only
    1541     * digit characters.</p>
    1542     *
    1543     * <p>{@code Null} and empty String will return
    1544     * {@code false}.</p>
    1545     *
    1546     * @param str  the {@code String} to check
    1547     * @return {@code true} if str contains only Unicode numeric
    1548     */
    1549    public static boolean isDigits(final String str) {
    1550        return StringUtils.isNumeric(str);
    1551    }
    1552
    1553    /**
    1554     * <p>Checks whether the String a valid Java number.</p>
    1555     *
    1556     * <p>Valid numbers include hexadecimal marked with the {@code 0x} or
    1557     * {@code 0X} qualifier, octal numbers, scientific notation and
    1558     * numbers marked with a type qualifier (e.g. 123L).</p>
    1559     *
    1560     * <p>Non-hexadecimal strings beginning with a leading zero are
    1561     * treated as octal values. Thus the string {@code 09} will return
    1562     * {@code false}, since {@code 9} is not a valid octal value.
    1563     * However, numbers beginning with {@code 0.} are treated as decimal.</p>
    1564     *
    1565     * <p>{@code null} and empty/blank {@code String} will return
    1566     * {@code false}.</p>
    1567     *
    1568     * <p>Note, {@link #createNumber(String)} should return a number for every
    1569     * input resulting in {@code true}.</p>
    1570     *
    1571     * @param str  the {@code String} to check
    1572     * @return {@code true} if the string is a correctly formatted number
    1573     * @since 3.3 the code supports hex {@code 0Xhhh} an
    1574     *        octal {@code 0ddd} validation
    1575     * @deprecated This feature will be removed in Lang 4.0,
    1576     *             use {@link NumberUtils#isCreatable(String)} instead
    1577     */
    1578    @Deprecated
    1579    public static boolean isNumber(final String str) {
    1580        return isCreatable(str);
    1581    }
    1582
    1583    /**
    1584     * <p>Checks whether the String a valid Java number.</p>
    1585     *
    1586     * <p>Valid numbers include hexadecimal marked with the {@code 0x} or
    1587     * {@code 0X} qualifier, octal numbers, scientific notation and
    1588     * numbers marked with a type qualifier (e.g. 123L).</p>
    1589     *
    1590     * <p>Non-hexadecimal strings beginning with a leading zero are
    1591     * treated as octal values. Thus the string {@code 09} will return
    1592     * {@code false}, since {@code 9} is not a valid octal value.
    1593     * However, numbers beginning with {@code 0.} are treated as decimal.</p>
    1594     *
    1595     * <p>{@code null} and empty/blank {@code String} will return
    1596     * {@code false}.</p>
    1597     *
    1598     * <p>Note, {@link #createNumber(String)} should return a number for every
    1599     * input resulting in {@code true}.</p>
    1600     *
    1601     * @param str  the {@code String} to check
    1602     * @return {@code true} if the string is a correctly formatted number
    1603     * @since 3.5
    1604     */
    1605    public static boolean isCreatable(final String str) {
    1606        if (StringUtils.isEmpty(str)) {
    1607            return false;
    1608        }
    1609        final char[] chars = str.toCharArray();
    1610        int sz = chars.length;
    1611        boolean hasExp = false;
    1612        boolean hasDecPoint = false;
    1613        boolean allowSigns = false;
    1614        boolean foundDigit = false;
    1615        // deal with any possible sign up front
    1616        final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0;
    1617        if (sz > start + 1 && chars[start] == '0' && !StringUtils.contains(str, '.')) { // leading 0, skip if is a decimal number
    1618            if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X
    1619                int i = start + 2;
    1620                if (i == sz) {
    1621                    return false; // str == "0x"
    1622                }
    1623                // checking hex (it can't be anything else)
    1624                for (; i < chars.length; i++) {
    1625                    if ((chars[i] < '0' || chars[i] > '9')
    1626                        && (chars[i] < 'a' || chars[i] > 'f')
    1627                        && (chars[i] < 'A' || chars[i] > 'F')) {
    1628                        return false;
    1629                    }
    1630                }
    1631                return true;
    1632           } else if (Character.isDigit(chars[start + 1])) {
    1633               // leading 0, but not hex, must be octal
    1634               int i = start + 1;
    1635               for (; i < chars.length; i++) {
    1636                   if (chars[i] < '0' || chars[i] > '7') {
    1637                       return false;
    1638                   }
    1639               }
    1640               return true;
    1641           }
    1642        }
    1643        sz--; // don't want to loop to the last char, check it afterwords
    1644              // for type qualifiers
    1645        int i = start;
    1646        // loop to the next to last char or to the last char if we need another digit to
    1647        // make a valid number (e.g. chars[0..5] = "1234E")
    1648        while (i < sz || i < sz + 1 && allowSigns && !foundDigit) {
    1649            if (chars[i] >= '0' && chars[i] <= '9') {
    1650                foundDigit = true;
    1651                allowSigns = false;
    1652
    1653            } else if (chars[i] == '.') {
    1654                if (hasDecPoint || hasExp) {
    1655                    // two decimal points or dec in exponent
    1656                    return false;
    1657                }
    1658                hasDecPoint = true;
    1659            } else if (chars[i] == 'e' || chars[i] == 'E') {
    1660                // we've already taken care of hex.
    1661                if (hasExp) {
    1662                    // two E's
    1663                    return false;
    1664                }
    1665                if (!foundDigit) {
    1666                    return false;
    1667                }
    1668                hasExp = true;
    1669                allowSigns = true;
    1670            } else if (chars[i] == '+' || chars[i] == '-') {
    1671                if (!allowSigns) {
    1672                    return false;
    1673                }
    1674                allowSigns = false;
    1675                foundDigit = false; // we need a digit after the E
    1676            } else {
    1677                return false;
    1678            }
    1679            i++;
    1680        }
    1681        if (i < chars.length) {
    1682            if (chars[i] >= '0' && chars[i] <= '9') {
    1683                // no type qualifier, OK
    1684                return true;
    1685            }
    1686            if (chars[i] == 'e' || chars[i] == 'E') {
    1687                // can't have an E at the last byte
    1688                return false;
    1689            }
    1690            if (chars[i] == '.') {
    1691                if (hasDecPoint || hasExp) {
    1692                    // two decimal points or dec in exponent
    1693                    return false;
    1694                }
    1695                // single trailing decimal point after non-exponent is ok
    1696                return foundDigit;
    1697            }
    1698            if (!allowSigns
    1699                && (chars[i] == 'd'
    1700                    || chars[i] == 'D'
    1701                    || chars[i] == 'f'
    1702                    || chars[i] == 'F')) {
    1703                return foundDigit;
    1704            }
    1705            if (chars[i] == 'l'
    1706                || chars[i] == 'L') {
    1707                // not allowing L with an exponent or decimal point
    1708                return foundDigit && !hasExp && !hasDecPoint;
    1709            }
    1710            // last character is illegal
    1711            return false;
    1712        }
    1713        // allowSigns is true iff the val ends in 'E'
    1714        // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
    1715        return !allowSigns && foundDigit;
    1716    }
    1717
    1718    /**
    1719     * <p>Checks whether the given String is a parsable number.</p>
    1720     *
    1721     * <p>Parsable numbers include those Strings understood by {@link Integer#parseInt(String)},
    1722     * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or
    1723     * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException}
    1724     * when calling one of those methods.</p>
    1725     *
    1726     * <p>Hexadecimal and scientific notations are <strong>not</strong> considered parsable.
    1727     * See {@link #isCreatable(String)} on those cases.</p>
    1728     *
    1729     * <p>{@code Null} and empty String will return {@code false}.</p>
    1730     *
    1731     * @param str the String to check.
    1732     * @return {@code true} if the string is a parsable number.
    1733     * @since 3.4
    1734     */
    1735    public static boolean isParsable(final String str) {
    1736        if (StringUtils.isEmpty(str)) {
    1737            return false;
    1738        }
    1739        if (str.charAt(str.length() - 1) == '.') {
    1740            return false;
    1741        }
    1742        if (str.charAt(0) == '-') {
    1743            if (str.length() == 1) {
    1744                return false;
    1745            }
    1746            return withDecimalsParsing(str, 1);
    1747        }
    1748        return withDecimalsParsing(str, 0);
    1749    }
    1750
    1751    private static boolean withDecimalsParsing(final String str, final int beginIdx) {
    1752        int decimalPoints = 0;
    1753        for (int i = beginIdx; i < str.length(); i++) {
    1754            final boolean isDecimalPoint = str.charAt(i) == '.';
    1755            if (isDecimalPoint) {
    1756                decimalPoints++;
    1757            }
    1758            if (decimalPoints > 1) {
    1759                return false;
    1760            }
    1761            if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) {
    1762                return false;
    1763            }
    1764        }
    1765        return true;
    1766    }
    1767
    1768    /**
    1769     * <p>Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.</p>
    1770     *
    1771     * @param x the first {@code int} to compare
    1772     * @param y the second {@code int} to compare
    1773     * @return the value {@code 0} if {@code x == y};
    1774     *         a value less than {@code 0} if {@code x < y}; and
    1775     *         a value greater than {@code 0} if {@code x > y}
    1776     * @since 3.4
    1777     */
    1778    public static int compare(final int x, final int y) {
    1779        if (x == y) {
    1780            return 0;
    1781        }
    1782        return x < y ? -1 : 1;
    1783    }
    1784
    1785    /**
    1786     * <p>Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.</p>
    1787     *
    1788     * @param x the first {@code long} to compare
    1789     * @param y the second {@code long} to compare
    1790     * @return the value {@code 0} if {@code x == y};
    1791     *         a value less than {@code 0} if {@code x < y}; and
    1792     *         a value greater than {@code 0} if {@code x > y}
    1793     * @since 3.4
    1794     */
    1795    public static int compare(final long x, final long y) {
    1796        if (x == y) {
    1797            return 0;
    1798        }
    1799        return x < y ? -1 : 1;
    1800    }
    1801
    1802    /**
    1803     * <p>Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.</p>
    1804     *
    1805     * @param x the first {@code short} to compare
    1806     * @param y the second {@code short} to compare
    1807     * @return the value {@code 0} if {@code x == y};
    1808     *         a value less than {@code 0} if {@code x < y}; and
    1809     *         a value greater than {@code 0} if {@code x > y}
    1810     * @since 3.4
    1811     */
    1812    public static int compare(final short x, final short y) {
    1813        if (x == y) {
    1814            return 0;
    1815        }
    1816        return x < y ? -1 : 1;
    1817    }
    1818
    1819    /**
    1820     * <p>Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.</p>
    1821     *
    1822     * @param x the first {@code byte} to compare
    1823     * @param y the second {@code byte} to compare
    1824     * @return the value {@code 0} if {@code x == y};
    1825     *         a value less than {@code 0} if {@code x < y}; and
    1826     *         a value greater than {@code 0} if {@code x > y}
    1827     * @since 3.4
    1828     */
    1829    public static int compare(final byte x, final byte y) {
    1830        return x - y;
    1831    }
    1832}