NumberUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3.math;

  18. import java.lang.reflect.Array;
  19. import java.math.BigDecimal;
  20. import java.math.BigInteger;
  21. import java.math.RoundingMode;
  22. import java.util.Objects;

  23. import org.apache.commons.lang3.StringUtils;
  24. import org.apache.commons.lang3.Validate;

  25. /**
  26.  * Provides extra functionality for Java Number classes.
  27.  *
  28.  * @since 2.0
  29.  */
  30. public class NumberUtils {

  31.     /** Reusable Long constant for zero. */
  32.     public static final Long LONG_ZERO = Long.valueOf(0L);
  33.     /** Reusable Long constant for one. */
  34.     public static final Long LONG_ONE = Long.valueOf(1L);
  35.     /** Reusable Long constant for minus one. */
  36.     public static final Long LONG_MINUS_ONE = Long.valueOf(-1L);
  37.     /** Reusable Integer constant for zero. */
  38.     public static final Integer INTEGER_ZERO = Integer.valueOf(0);
  39.     /** Reusable Integer constant for one. */
  40.     public static final Integer INTEGER_ONE = Integer.valueOf(1);
  41.     /** Reusable Integer constant for two */
  42.     public static final Integer INTEGER_TWO = Integer.valueOf(2);
  43.     /** Reusable Integer constant for minus one. */
  44.     public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1);
  45.     /** Reusable Short constant for zero. */
  46.     public static final Short SHORT_ZERO = Short.valueOf((short) 0);
  47.     /** Reusable Short constant for one. */
  48.     public static final Short SHORT_ONE = Short.valueOf((short) 1);
  49.     /** Reusable Short constant for minus one. */
  50.     public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1);
  51.     /** Reusable Byte constant for zero. */
  52.     public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);
  53.     /** Reusable Byte constant for one. */
  54.     public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);
  55.     /** Reusable Byte constant for minus one. */
  56.     public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1);
  57.     /** Reusable Double constant for zero. */
  58.     public static final Double DOUBLE_ZERO = Double.valueOf(0.0d);
  59.     /** Reusable Double constant for one. */
  60.     public static final Double DOUBLE_ONE = Double.valueOf(1.0d);
  61.     /** Reusable Double constant for minus one. */
  62.     public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d);
  63.     /** Reusable Float constant for zero. */
  64.     public static final Float FLOAT_ZERO = Float.valueOf(0.0f);
  65.     /** Reusable Float constant for one. */
  66.     public static final Float FLOAT_ONE = Float.valueOf(1.0f);
  67.     /** Reusable Float constant for minus one. */
  68.     public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);

  69.     /**
  70.      * {@link Integer#MAX_VALUE} as a {@link Long}.
  71.      *
  72.      * @since 3.12.0
  73.      */
  74.     public static final Long LONG_INT_MAX_VALUE = Long.valueOf(Integer.MAX_VALUE);

  75.     /**
  76.      * {@link Integer#MIN_VALUE} as a {@link Long}.
  77.      *
  78.      * @since 3.12.0
  79.      */
  80.     public static final Long LONG_INT_MIN_VALUE = Long.valueOf(Integer.MIN_VALUE);

  81.     /**
  82.      * Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.
  83.      *
  84.      * @param x the first {@code byte} to compare
  85.      * @param y the second {@code byte} to compare
  86.      * @return the value {@code 0} if {@code x == y};
  87.      *         a value less than {@code 0} if {@code x < y}; and
  88.      *         a value greater than {@code 0} if {@code x > y}
  89.      * @since 3.4
  90.      */
  91.     public static int compare(final byte x, final byte y) {
  92.         return x - y;
  93.     }

  94.     /**
  95.      * Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.
  96.      *
  97.      * @param x the first {@code int} to compare
  98.      * @param y the second {@code int} to compare
  99.      * @return the value {@code 0} if {@code x == y};
  100.      *         a value less than {@code 0} if {@code x < y}; and
  101.      *         a value greater than {@code 0} if {@code x > y}
  102.      * @since 3.4
  103.      */
  104.     public static int compare(final int x, final int y) {
  105.         if (x == y) {
  106.             return 0;
  107.         }
  108.         return x < y ? -1 : 1;
  109.     }

  110.     /**
  111.      * Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.
  112.      *
  113.      * @param x the first {@code long} to compare
  114.      * @param y the second {@code long} to compare
  115.      * @return the value {@code 0} if {@code x == y};
  116.      *         a value less than {@code 0} if {@code x < y}; and
  117.      *         a value greater than {@code 0} if {@code x > y}
  118.      * @since 3.4
  119.      */
  120.     public static int compare(final long x, final long y) {
  121.         if (x == y) {
  122.             return 0;
  123.         }
  124.         return x < y ? -1 : 1;
  125.     }

  126.     /**
  127.      * Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.
  128.      *
  129.      * @param x the first {@code short} to compare
  130.      * @param y the second {@code short} to compare
  131.      * @return the value {@code 0} if {@code x == y};
  132.      *         a value less than {@code 0} if {@code x < y}; and
  133.      *         a value greater than {@code 0} if {@code x > y}
  134.      * @since 3.4
  135.      */
  136.     public static int compare(final short x, final short y) {
  137.         if (x == y) {
  138.             return 0;
  139.         }
  140.         return x < y ? -1 : 1;
  141.     }

  142.     /**
  143.      * Creates a {@link BigDecimal} from a {@link String}.
  144.      *
  145.      * <p>Returns {@code null} if the string is {@code null}.</p>
  146.      *
  147.      * @param str  a {@link String} to convert, may be null
  148.      * @return converted {@link BigDecimal} (or null if the input is null)
  149.      * @throws NumberFormatException if the value cannot be converted
  150.      */
  151.     public static BigDecimal createBigDecimal(final String str) {
  152.         if (str == null) {
  153.             return null;
  154.         }
  155.         // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
  156.         if (StringUtils.isBlank(str)) {
  157.             throw new NumberFormatException("A blank string is not a valid number");
  158.         }
  159.         return new BigDecimal(str);
  160.     }

  161.     /**
  162.      * Creates a {@link BigInteger} from a {@link String}.
  163.      *
  164.      * Handles hexadecimal (0x or #) and octal (0) notations.
  165.      *
  166.      * <p>Returns {@code null} if the string is {@code null}.</p>
  167.      *
  168.      * @param str  a {@link String} to convert, may be null
  169.      * @return converted {@link BigInteger} (or null if the input is null)
  170.      * @throws NumberFormatException if the value cannot be converted
  171.      * @since 3.2
  172.      */
  173.     public static BigInteger createBigInteger(final String str) {
  174.         if (str == null) {
  175.             return null;
  176.         }
  177.         if (str.isEmpty()) {
  178.             throw new NumberFormatException("An empty string is not a valid number");
  179.         }
  180.         int pos = 0; // offset within string
  181.         int radix = 10;
  182.         boolean negate = false; // need to negate later?
  183.         final char char0 = str.charAt(0);
  184.         if (char0 == '-') {
  185.             negate = true;
  186.             pos = 1;
  187.         } else if (char0 == '+') {
  188.             pos = 1;
  189.         }
  190.         if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex
  191.             radix = 16;
  192.             pos += 2;
  193.         } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
  194.             radix = 16;
  195.             pos++;
  196.         } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
  197.             radix = 8;
  198.             pos++;
  199.         } // default is to treat as decimal

  200.         final BigInteger value = new BigInteger(str.substring(pos), radix);
  201.         return negate ? value.negate() : value;
  202.     }

  203.     /**
  204.      * Creates a {@link Double} from a {@link String}.
  205.      *
  206.      * <p>Returns {@code null} if the string is {@code null}.</p>
  207.      *
  208.      * @param str  a {@link String} to convert, may be null
  209.      * @return converted {@link Double} (or null if the input is null)
  210.      * @throws NumberFormatException if the value cannot be converted
  211.      */
  212.     public static Double createDouble(final String str) {
  213.         if (str == null) {
  214.             return null;
  215.         }
  216.         return Double.valueOf(str);
  217.     }

  218.     /**
  219.      * Creates a {@link Float} from a {@link String}.
  220.      *
  221.      * <p>Returns {@code null} if the string is {@code null}.</p>
  222.      *
  223.      * @param str  a {@link String} to convert, may be null
  224.      * @return converted {@link Float} (or null if the input is null)
  225.      * @throws NumberFormatException if the value cannot be converted
  226.      */
  227.     public static Float createFloat(final String str) {
  228.         if (str == null) {
  229.             return null;
  230.         }
  231.         return Float.valueOf(str);
  232.     }

  233.     /**
  234.      * Creates an {@link Integer} from a {@link String}.
  235.      *
  236.      * Handles hexadecimal (0xhhhh) and octal (0dddd) notations.
  237.      * N.B. a leading zero means octal; spaces are not trimmed.
  238.      *
  239.      * <p>Returns {@code null} if the string is {@code null}.</p>
  240.      *
  241.      * @param str  a {@link String} to convert, may be null
  242.      * @return converted {@link Integer} (or null if the input is null)
  243.      * @throws NumberFormatException if the value cannot be converted
  244.      */
  245.     public static Integer createInteger(final String str) {
  246.         if (str == null) {
  247.             return null;
  248.         }
  249.         // decode() handles 0xAABD and 0777 (hex and octal) as well.
  250.         return Integer.decode(str);
  251.     }

  252.     /**
  253.      * Creates a {@link Long} from a {@link String}.
  254.      *
  255.      * Handles hexadecimal (0Xhhhh) and octal (0ddd) notations.
  256.      * N.B. a leading zero means octal; spaces are not trimmed.
  257.      *
  258.      * <p>Returns {@code null} if the string is {@code null}.</p>
  259.      *
  260.      * @param str  a {@link String} to convert, may be null
  261.      * @return converted {@link Long} (or null if the input is null)
  262.      * @throws NumberFormatException if the value cannot be converted
  263.      * @since 3.1
  264.      */
  265.     public static Long createLong(final String str) {
  266.         if (str == null) {
  267.             return null;
  268.         }
  269.         return Long.decode(str);
  270.     }

  271.     /**
  272.      * Creates a {@link Number} from a {@link String}.
  273.      *
  274.      * <p>If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it
  275.      * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the
  276.      * prefix is more than 8 - or BigInteger if there are more than 16 digits.
  277.      * </p>
  278.      * <p>Then, the value is examined for a type qualifier on the end, i.e. one of
  279.      * {@code 'f', 'F', 'd', 'D', 'l', 'L'}.  If it is found, it starts
  280.      * trying to create successively larger types from the type specified
  281.      * until one is found that can represent the value.</p>
  282.      *
  283.      * <p>If a type specifier is not found, it will check for a decimal point
  284.      * and then try successively larger types from {@link Integer} to
  285.      * {@link BigInteger} and from {@link Float} to
  286.      * {@link BigDecimal}.</p>
  287.      *
  288.      * <p>
  289.      * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
  290.      * be Integer, Long or BigDecimal as appropriate.
  291.      * </p>
  292.      *
  293.      * <p>Returns {@code null} if the string is {@code null}.</p>
  294.      *
  295.      * <p>This method does not trim the input string, i.e., strings with leading
  296.      * or trailing spaces will generate NumberFormatExceptions.</p>
  297.      *
  298.      * @param str  String containing a number, may be null
  299.      * @return Number created from the string (or null if the input is null)
  300.      * @throws NumberFormatException if the value cannot be converted
  301.      */
  302.     public static Number createNumber(final String str) {
  303.         if (str == null) {
  304.             return null;
  305.         }
  306.         if (StringUtils.isBlank(str)) {
  307.             throw new NumberFormatException("A blank string is not a valid number");
  308.         }
  309.         // Need to deal with all possible hex prefixes here
  310.         final String[] hexPrefixes = {"0x", "0X", "#"};
  311.         final int length = str.length();
  312.         final int offset = str.charAt(0) == '+' || str.charAt(0) == '-' ? 1 : 0;
  313.         int pfxLen = 0;
  314.         for (final String pfx : hexPrefixes) {
  315.             if (str.startsWith(pfx, offset)) {
  316.                 pfxLen += pfx.length() + offset;
  317.                 break;
  318.             }
  319.         }
  320.         if (pfxLen > 0) { // we have a hex number
  321.             char firstSigDigit = 0; // strip leading zeroes
  322.             for (int i = pfxLen; i < length; i++) {
  323.                 firstSigDigit = str.charAt(i);
  324.                 if (firstSigDigit != '0') {
  325.                     break;
  326.                 }
  327.                 pfxLen++;
  328.             }
  329.             final int hexDigits = length - pfxLen;
  330.             if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long
  331.                 return createBigInteger(str);
  332.             }
  333.             if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int
  334.                 return createLong(str);
  335.             }
  336.             return createInteger(str);
  337.         }
  338.         final char lastChar = str.charAt(length - 1);
  339.         final String mant;
  340.         final String dec;
  341.         final String exp;
  342.         final int decPos = str.indexOf('.');
  343.         final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
  344.         // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
  345.         // and the parsing which will detect if e or E appear in a number due to using the wrong offset

  346.         // Detect if the return type has been requested
  347.         final boolean requestType = !Character.isDigit(lastChar) && lastChar != '.';
  348.         if (decPos > -1) { // there is a decimal point
  349.             if (expPos > -1) { // there is an exponent
  350.                 if (expPos <= decPos || expPos > length) { // prevents double exponent causing IOOBE
  351.                     throw new NumberFormatException(str + " is not a valid number.");
  352.                 }
  353.                 dec = str.substring(decPos + 1, expPos);
  354.             } else {
  355.                 // No exponent, but there may be a type character to remove
  356.                 dec = str.substring(decPos + 1, requestType ? length - 1 : length);
  357.             }
  358.             mant = getMantissa(str, decPos);
  359.         } else {
  360.             if (expPos > -1) {
  361.                 if (expPos > length) { // prevents double exponent causing IOOBE
  362.                     throw new NumberFormatException(str + " is not a valid number.");
  363.                 }
  364.                 mant = getMantissa(str, expPos);
  365.             } else {
  366.                 // No decimal, no exponent, but there may be a type character to remove
  367.                 mant = getMantissa(str, requestType ? length - 1 : length);
  368.             }
  369.             dec = null;
  370.         }
  371.         if (requestType) {
  372.             if (expPos > -1 && expPos < length - 1) {
  373.                 exp = str.substring(expPos + 1, length - 1);
  374.             } else {
  375.                 exp = null;
  376.             }
  377.             //Requesting a specific type.
  378.             final String numeric = str.substring(0, length - 1);
  379.             switch (lastChar) {
  380.                 case 'l' :
  381.                 case 'L' :
  382.                     if (dec == null
  383.                         && exp == null
  384.                         && (!numeric.isEmpty() && numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
  385.                         try {
  386.                             return createLong(numeric);
  387.                         } catch (final NumberFormatException ignored) {
  388.                             // Too big for a long
  389.                         }
  390.                         return createBigInteger(numeric);

  391.                     }
  392.                     throw new NumberFormatException(str + " is not a valid number.");
  393.                 case 'f' :
  394.                 case 'F' :
  395.                     try {
  396.                         final Float f = createFloat(str);
  397.                         if (!(f.isInfinite() || f.floatValue() == 0.0F && !isZero(mant, dec))) {
  398.                             //If it's too big for a float or the float value = 0 and the string
  399.                             //has non-zeros in it, then float does not have the precision we want
  400.                             return f;
  401.                         }

  402.                     } catch (final NumberFormatException ignored) {
  403.                         // ignore the bad number
  404.                     }
  405.                     //$FALL-THROUGH$
  406.                 case 'd' :
  407.                 case 'D' :
  408.                     try {
  409.                         final Double d = createDouble(str);
  410.                         if (!(d.isInfinite() || d.doubleValue() == 0.0D && !isZero(mant, dec))) {
  411.                             return d;
  412.                         }
  413.                     } catch (final NumberFormatException ignored) {
  414.                         // ignore the bad number
  415.                     }
  416.                     try {
  417.                         return createBigDecimal(numeric);
  418.                     } catch (final NumberFormatException ignored) {
  419.                         // ignore the bad number
  420.                     }
  421.                     //$FALL-THROUGH$
  422.                 default :
  423.                     throw new NumberFormatException(str + " is not a valid number.");

  424.             }
  425.         }
  426.         //User doesn't have a preference on the return type, so let's start
  427.         //small and go from there...
  428.         if (expPos > -1 && expPos < length - 1) {
  429.             exp = str.substring(expPos + 1);
  430.         } else {
  431.             exp = null;
  432.         }
  433.         if (dec == null && exp == null) { // no decimal point and no exponent
  434.             //Must be an Integer, Long, Biginteger
  435.             try {
  436.                 return createInteger(str);
  437.             } catch (final NumberFormatException ignored) {
  438.                 // ignore the bad number
  439.             }
  440.             try {
  441.                 return createLong(str);
  442.             } catch (final NumberFormatException ignored) {
  443.                 // ignore the bad number
  444.             }
  445.             return createBigInteger(str);
  446.         }

  447.         //Must be a Float, Double, BigDecimal
  448.         try {
  449.             final Float f = createFloat(str);
  450.             final Double d = createDouble(str);
  451.             if (!f.isInfinite()
  452.                     && !(f.floatValue() == 0.0F && !isZero(mant, dec))
  453.                     && f.toString().equals(d.toString())) {
  454.                 return f;
  455.             }
  456.             if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !isZero(mant, dec))) {
  457.                 final BigDecimal b = createBigDecimal(str);
  458.                 if (b.compareTo(BigDecimal.valueOf(d.doubleValue())) == 0) {
  459.                     return d;
  460.                 }
  461.                 return b;
  462.             }
  463.         } catch (final NumberFormatException ignored) {
  464.             // ignore the bad number
  465.         }
  466.         return createBigDecimal(str);
  467.     }

  468.      /**
  469.      * Utility method for {@link #createNumber(String)}.
  470.      *
  471.      * <p>Returns mantissa of the given number.</p>
  472.      *
  473.      * @param str the string representation of the number
  474.      * @param stopPos the position of the exponent or decimal point
  475.      * @return mantissa of the given number
  476.      * @throws NumberFormatException if no mantissa can be retrieved
  477.      */
  478.     private static String getMantissa(final String str, final int stopPos) {
  479.          final char firstChar = str.charAt(0);
  480.          final boolean hasSign = firstChar == '-' || firstChar == '+';
  481.          final int length = str.length();
  482.          if (length <= (hasSign ? 1 : 0) || length < stopPos) {
  483.              throw new NumberFormatException(str + " is not a valid number.");
  484.          }
  485.          return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos);
  486.     }

  487.     /**
  488.      * Utility method for {@link #createNumber(java.lang.String)}.
  489.      *
  490.      * <p>Returns {@code true} if s is {@code null} or empty.</p>
  491.      *
  492.      * @param str the String to check
  493.      * @return if it is all zeros or {@code null}
  494.      */
  495.     private static boolean isAllZeros(final String str) {
  496.         if (str == null) {
  497.             return true;
  498.         }
  499.         for (int i = str.length() - 1; i >= 0; i--) {
  500.             if (str.charAt(i) != '0') {
  501.                 return false;
  502.             }
  503.         }
  504.         return true;
  505.     }

  506.     /**
  507.      * Checks whether the String is a valid Java number.
  508.      *
  509.      * <p>Valid numbers include hexadecimal marked with the {@code 0x} or
  510.      * {@code 0X} qualifier, octal numbers, scientific notation and
  511.      * numbers marked with a type qualifier (e.g. 123L).</p>
  512.      *
  513.      * <p>Non-hexadecimal strings beginning with a leading zero are
  514.      * treated as octal values. Thus the string {@code 09} will return
  515.      * {@code false}, since {@code 9} is not a valid octal value.
  516.      * However, numbers beginning with {@code 0.} are treated as decimal.</p>
  517.      *
  518.      * <p>{@code null} and empty/blank {@link String} will return
  519.      * {@code false}.</p>
  520.      *
  521.      * <p>Note, {@link #createNumber(String)} should return a number for every
  522.      * input resulting in {@code true}.</p>
  523.      *
  524.      * @param str  the {@link String} to check
  525.      * @return {@code true} if the string is a correctly formatted number
  526.      * @since 3.5
  527.      */
  528.     public static boolean isCreatable(final String str) {
  529.         if (StringUtils.isEmpty(str)) {
  530.             return false;
  531.         }
  532.         final char[] chars = str.toCharArray();
  533.         int sz = chars.length;
  534.         boolean hasExp = false;
  535.         boolean hasDecPoint = false;
  536.         boolean allowSigns = false;
  537.         boolean foundDigit = false;
  538.         // deal with any possible sign up front
  539.         final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0;
  540.         if (sz > start + 1 && chars[start] == '0' && !StringUtils.contains(str, '.')) { // leading 0, skip if is a decimal number
  541.             if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X
  542.                 int i = start + 2;
  543.                 if (i == sz) {
  544.                     return false; // str == "0x"
  545.                 }
  546.                 // checking hex (it can't be anything else)
  547.                 for (; i < chars.length; i++) {
  548.                     if ((chars[i] < '0' || chars[i] > '9')
  549.                         && (chars[i] < 'a' || chars[i] > 'f')
  550.                         && (chars[i] < 'A' || chars[i] > 'F')) {
  551.                         return false;
  552.                     }
  553.                 }
  554.                 return true;
  555.            }
  556.             if (Character.isDigit(chars[start + 1])) {
  557.                    // leading 0, but not hex, must be octal
  558.                    int i = start + 1;
  559.                    for (; i < chars.length; i++) {
  560.                        if (chars[i] < '0' || chars[i] > '7') {
  561.                            return false;
  562.                        }
  563.                    }
  564.                    return true;
  565.                }
  566.         }
  567.         sz--; // don't want to loop to the last char, check it afterwards
  568.               // for type qualifiers
  569.         int i = start;
  570.         // loop to the next to last char or to the last char if we need another digit to
  571.         // make a valid number (e.g. chars[0..5] = "1234E")
  572.         while (i < sz || i < sz + 1 && allowSigns && !foundDigit) {
  573.             if (chars[i] >= '0' && chars[i] <= '9') {
  574.                 foundDigit = true;
  575.                 allowSigns = false;

  576.             } else if (chars[i] == '.') {
  577.                 if (hasDecPoint || hasExp) {
  578.                     // two decimal points or dec in exponent
  579.                     return false;
  580.                 }
  581.                 hasDecPoint = true;
  582.             } else if (chars[i] == 'e' || chars[i] == 'E') {
  583.                 // we've already taken care of hex.
  584.                 if (hasExp) {
  585.                     // two E's
  586.                     return false;
  587.                 }
  588.                 if (!foundDigit) {
  589.                     return false;
  590.                 }
  591.                 hasExp = true;
  592.                 allowSigns = true;
  593.             } else if (chars[i] == '+' || chars[i] == '-') {
  594.                 if (!allowSigns) {
  595.                     return false;
  596.                 }
  597.                 allowSigns = false;
  598.                 foundDigit = false; // we need a digit after the E
  599.             } else {
  600.                 return false;
  601.             }
  602.             i++;
  603.         }
  604.         if (i < chars.length) {
  605.             if (chars[i] >= '0' && chars[i] <= '9') {
  606.                 // no type qualifier, OK
  607.                 return true;
  608.             }
  609.             if (chars[i] == 'e' || chars[i] == 'E') {
  610.                 // can't have an E at the last byte
  611.                 return false;
  612.             }
  613.             if (chars[i] == '.') {
  614.                 if (hasDecPoint || hasExp) {
  615.                     // two decimal points or dec in exponent
  616.                     return false;
  617.                 }
  618.                 // single trailing decimal point after non-exponent is ok
  619.                 return foundDigit;
  620.             }
  621.             if (!allowSigns
  622.                 && (chars[i] == 'd'
  623.                     || chars[i] == 'D'
  624.                     || chars[i] == 'f'
  625.                     || chars[i] == 'F')) {
  626.                 return foundDigit;
  627.             }
  628.             if (chars[i] == 'l'
  629.                 || chars[i] == 'L') {
  630.                 // not allowing L with an exponent or decimal point
  631.                 return foundDigit && !hasExp && !hasDecPoint;
  632.             }
  633.             // last character is illegal
  634.             return false;
  635.         }
  636.         // allowSigns is true iff the val ends in 'E'
  637.         // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
  638.         return !allowSigns && foundDigit;
  639.     }

  640.     /**
  641.      * Checks whether the {@link String} contains only
  642.      * digit characters.
  643.      *
  644.      * <p>{@code null} and empty String will return
  645.      * {@code false}.</p>
  646.      *
  647.      * @param str  the {@link String} to check
  648.      * @return {@code true} if str contains only Unicode numeric
  649.      */
  650.     public static boolean isDigits(final String str) {
  651.         return StringUtils.isNumeric(str);
  652.     }

  653.     /**
  654.      * Checks whether the String is a valid Java number.
  655.      *
  656.      * <p>Valid numbers include hexadecimal marked with the {@code 0x} or
  657.      * {@code 0X} qualifier, octal numbers, scientific notation and
  658.      * numbers marked with a type qualifier (e.g. 123L).</p>
  659.      *
  660.      * <p>Non-hexadecimal strings beginning with a leading zero are
  661.      * treated as octal values. Thus the string {@code 09} will return
  662.      * {@code false}, since {@code 9} is not a valid octal value.
  663.      * However, numbers beginning with {@code 0.} are treated as decimal.</p>
  664.      *
  665.      * <p>{@code null} and empty/blank {@link String} will return
  666.      * {@code false}.</p>
  667.      *
  668.      * <p>Note, {@link #createNumber(String)} should return a number for every
  669.      * input resulting in {@code true}.</p>
  670.      *
  671.      * @param str  the {@link String} to check
  672.      * @return {@code true} if the string is a correctly formatted number
  673.      * @since 3.3 the code supports hexadecimal {@code 0Xhhh} an
  674.      *        octal {@code 0ddd} validation
  675.      * @deprecated This feature will be removed in Lang 4,
  676.      *             use {@link NumberUtils#isCreatable(String)} instead
  677.      */
  678.     @Deprecated
  679.     public static boolean isNumber(final String str) {
  680.         return isCreatable(str);
  681.     }

  682.     /**
  683.      * Checks whether the given String is a parsable number.
  684.      *
  685.      * <p>Parsable numbers include those Strings understood by {@link Integer#parseInt(String)},
  686.      * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or
  687.      * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException}
  688.      * when calling one of those methods.</p>
  689.      *
  690.      * <p>Hexadecimal and scientific notations are <strong>not</strong> considered parsable.
  691.      * See {@link #isCreatable(String)} on those cases.</p>
  692.      *
  693.      * <p>{@code null} and empty String will return {@code false}.</p>
  694.      *
  695.      * @param str the String to check.
  696.      * @return {@code true} if the string is a parsable number.
  697.      * @since 3.4
  698.      */
  699.     public static boolean isParsable(final String str) {
  700.         if (StringUtils.isEmpty(str)) {
  701.             return false;
  702.         }
  703.         if (str.charAt(str.length() - 1) == '.') {
  704.             return false;
  705.         }
  706.         if (str.charAt(0) == '-') {
  707.             if (str.length() == 1) {
  708.                 return false;
  709.             }
  710.             return withDecimalsParsing(str, 1);
  711.         }
  712.         return withDecimalsParsing(str, 0);
  713.     }

  714.     /**
  715.      * Utility method for {@link #createNumber(java.lang.String)}.
  716.      *
  717.      * <p>This will check if the magnitude of the number is zero by checking if there
  718.      * are only zeros before and after the decimal place.</p>
  719.      *
  720.      * <p>Note: It is <strong>assumed</strong> that the input string has been converted
  721.      * to either a Float or Double with a value of zero when this method is called.
  722.      * This eliminates invalid input for example {@code ".", ".D", ".e0"}.</p>
  723.      *
  724.      * <p>Thus the method only requires checking if both arguments are null, empty or
  725.      * contain only zeros.</p>
  726.      *
  727.      * <p>Given {@code s = mant + "." + dec}:</p>
  728.      * <ul>
  729.      * <li>{@code true} if s is {@code "0.0"}
  730.      * <li>{@code true} if s is {@code "0."}
  731.      * <li>{@code true} if s is {@code ".0"}
  732.      * <li>{@code false} otherwise (this assumes {@code "."} is not possible)
  733.      * </ul>
  734.      *
  735.      * @param mant the mantissa decimal digits before the decimal point (sign must be removed; never null)
  736.      * @param dec the decimal digits after the decimal point (exponent and type specifier removed;
  737.      *            can be null)
  738.      * @return true if the magnitude is zero
  739.      */
  740.     private static boolean isZero(final String mant, final String dec) {
  741.         return isAllZeros(mant) && isAllZeros(dec);
  742.     }

  743.     /**
  744.      * Returns the maximum value in an array.
  745.      *
  746.      * @param array  an array, must not be null or empty
  747.      * @return the maximum value in the array
  748.      * @throws NullPointerException if {@code array} is {@code null}
  749.      * @throws IllegalArgumentException if {@code array} is empty
  750.      * @since 3.4 Changed signature from max(byte[]) to max(byte...)
  751.      */
  752.     public static byte max(final byte... array) {
  753.         // Validates input
  754.         validateArray(array);
  755.         // Finds and returns max
  756.         byte max = array[0];
  757.         for (int i = 1; i < array.length; i++) {
  758.             if (array[i] > max) {
  759.                 max = array[i];
  760.             }
  761.         }
  762.         return max;
  763.     }

  764.     /**
  765.      * Gets the maximum of three {@code byte} values.
  766.      *
  767.      * @param a  value 1
  768.      * @param b  value 2
  769.      * @param c  value 3
  770.      * @return  the largest of the values
  771.      */
  772.     public static byte max(byte a, final byte b, final byte c) {
  773.         if (b > a) {
  774.             a = b;
  775.         }
  776.         if (c > a) {
  777.             a = c;
  778.         }
  779.         return a;
  780.     }

  781.     /**
  782.      * Returns the maximum value in an array.
  783.      *
  784.      * @param array  an array, must not be null or empty
  785.      * @return the maximum value in the array
  786.      * @throws NullPointerException if {@code array} is {@code null}
  787.      * @throws IllegalArgumentException if {@code array} is empty
  788.      * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
  789.      * @since 3.4 Changed signature from max(double[]) to max(double...)
  790.      */
  791.     public static double max(final double... array) {
  792.         // Validates input
  793.         validateArray(array);
  794.         // Finds and returns max
  795.         double max = array[0];
  796.         for (int j = 1; j < array.length; j++) {
  797.             if (Double.isNaN(array[j])) {
  798.                 return Double.NaN;
  799.             }
  800.             if (array[j] > max) {
  801.                 max = array[j];
  802.             }
  803.         }
  804.         return max;
  805.     }

  806.     /**
  807.      * Gets the maximum of three {@code double} values.
  808.      *
  809.      * <p>If any value is {@code NaN}, {@code NaN} is
  810.      * returned. Infinity is handled.</p>
  811.      *
  812.      * @param a  value 1
  813.      * @param b  value 2
  814.      * @param c  value 3
  815.      * @return  the largest of the values
  816.      * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently
  817.      */
  818.     public static double max(final double a, final double b, final double c) {
  819.         return Math.max(Math.max(a, b), c);
  820.     }

  821.     /**
  822.      * Returns the maximum value in an array.
  823.      *
  824.      * @param array  an array, must not be null or empty
  825.      * @return the maximum value in the array
  826.      * @throws NullPointerException if {@code array} is {@code null}
  827.      * @throws IllegalArgumentException if {@code array} is empty
  828.      * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
  829.      * @since 3.4 Changed signature from max(float[]) to max(float...)
  830.      */
  831.     public static float max(final float... array) {
  832.         // Validates input
  833.         validateArray(array);
  834.         // Finds and returns max
  835.         float max = array[0];
  836.         for (int j = 1; j < array.length; j++) {
  837.             if (Float.isNaN(array[j])) {
  838.                 return Float.NaN;
  839.             }
  840.             if (array[j] > max) {
  841.                 max = array[j];
  842.             }
  843.         }
  844.         return max;
  845.     }

  846.     // must handle Long, Float, Integer, Float, Short,
  847.     //                  BigDecimal, BigInteger and Byte
  848.     // useful methods:
  849.     // Byte.decode(String)
  850.     // Byte.valueOf(String, int radix)
  851.     // Byte.valueOf(String)
  852.     // Double.valueOf(String)
  853.     // Float.valueOf(String)
  854.     // Float.valueOf(String)
  855.     // Integer.valueOf(String, int radix)
  856.     // Integer.valueOf(String)
  857.     // Integer.decode(String)
  858.     // Integer.getInteger(String)
  859.     // Integer.getInteger(String, int val)
  860.     // Integer.getInteger(String, Integer val)
  861.     // Integer.valueOf(String)
  862.     // Double.valueOf(String)
  863.     // new Byte(String)
  864.     // Long.valueOf(String)
  865.     // Long.getLong(String)
  866.     // Long.getLong(String, int)
  867.     // Long.getLong(String, Integer)
  868.     // Long.valueOf(String, int)
  869.     // Long.valueOf(String)
  870.     // Short.valueOf(String)
  871.     // Short.decode(String)
  872.     // Short.valueOf(String, int)
  873.     // Short.valueOf(String)
  874.     // new BigDecimal(String)
  875.     // new BigInteger(String)
  876.     // new BigInteger(String, int radix)
  877.     // Possible inputs:
  878.     // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
  879.     // plus minus everything. Prolly more. A lot are not separable.

  880.     /**
  881.      * Gets the maximum of three {@code float} values.
  882.      *
  883.      * <p>If any value is {@code NaN}, {@code NaN} is
  884.      * returned. Infinity is handled.</p>
  885.      *
  886.      * @param a  value 1
  887.      * @param b  value 2
  888.      * @param c  value 3
  889.      * @return  the largest of the values
  890.      * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently
  891.      */
  892.     public static float max(final float a, final float b, final float c) {
  893.         return Math.max(Math.max(a, b), c);
  894.     }

  895.     /**
  896.      * Returns the maximum value in an array.
  897.      *
  898.      * @param array  an array, must not be null or empty
  899.      * @return the maximum value in the array
  900.      * @throws NullPointerException if {@code array} is {@code null}
  901.      * @throws IllegalArgumentException if {@code array} is empty
  902.      * @since 3.4 Changed signature from max(int[]) to max(int...)
  903.      */
  904.     public static int max(final int... array) {
  905.         // Validates input
  906.         validateArray(array);
  907.         // Finds and returns max
  908.         int max = array[0];
  909.         for (int j = 1; j < array.length; j++) {
  910.             if (array[j] > max) {
  911.                 max = array[j];
  912.             }
  913.         }
  914.         return max;
  915.     }

  916.     /**
  917.      * Gets the maximum of three {@code int} values.
  918.      *
  919.      * @param a  value 1
  920.      * @param b  value 2
  921.      * @param c  value 3
  922.      * @return  the largest of the values
  923.      */
  924.     public static int max(int a, final int b, final int c) {
  925.         if (b > a) {
  926.             a = b;
  927.         }
  928.         if (c > a) {
  929.             a = c;
  930.         }
  931.         return a;
  932.     }

  933.     /**
  934.      * Returns the maximum value in an array.
  935.      *
  936.      * @param array  an array, must not be null or empty
  937.      * @return the maximum value in the array
  938.      * @throws NullPointerException if {@code array} is {@code null}
  939.      * @throws IllegalArgumentException if {@code array} is empty
  940.      * @since 3.4 Changed signature from max(long[]) to max(long...)
  941.      */
  942.     public static long max(final long... array) {
  943.         // Validates input
  944.         validateArray(array);
  945.         // Finds and returns max
  946.         long max = array[0];
  947.         for (int j = 1; j < array.length; j++) {
  948.             if (array[j] > max) {
  949.                 max = array[j];
  950.             }
  951.         }
  952.         return max;
  953.     }

  954.     // 3 param max
  955.     /**
  956.      * Gets the maximum of three {@code long} values.
  957.      *
  958.      * @param a  value 1
  959.      * @param b  value 2
  960.      * @param c  value 3
  961.      * @return  the largest of the values
  962.      */
  963.     public static long max(long a, final long b, final long c) {
  964.         if (b > a) {
  965.             a = b;
  966.         }
  967.         if (c > a) {
  968.             a = c;
  969.         }
  970.         return a;
  971.     }

  972.     /**
  973.      * Returns the maximum value in an array.
  974.      *
  975.      * @param array  an array, must not be null or empty
  976.      * @return the maximum value in the array
  977.      * @throws NullPointerException if {@code array} is {@code null}
  978.      * @throws IllegalArgumentException if {@code array} is empty
  979.      * @since 3.4 Changed signature from max(short[]) to max(short...)
  980.      */
  981.     public static short max(final short... array) {
  982.         // Validates input
  983.         validateArray(array);

  984.         // Finds and returns max
  985.         short max = array[0];
  986.         for (int i = 1; i < array.length; i++) {
  987.             if (array[i] > max) {
  988.                 max = array[i];
  989.             }
  990.         }
  991.         return max;
  992.     }

  993.     /**
  994.      * Gets the maximum of three {@code short} values.
  995.      *
  996.      * @param a  value 1
  997.      * @param b  value 2
  998.      * @param c  value 3
  999.      * @return  the largest of the values
  1000.      */
  1001.     public static short max(short a, final short b, final short c) {
  1002.         if (b > a) {
  1003.             a = b;
  1004.         }
  1005.         if (c > a) {
  1006.             a = c;
  1007.         }
  1008.         return a;
  1009.     }

  1010.     /**
  1011.      * Returns the minimum value in an array.
  1012.      *
  1013.      * @param array  an array, must not be null or empty
  1014.      * @return the minimum value in the array
  1015.      * @throws NullPointerException if {@code array} is {@code null}
  1016.      * @throws IllegalArgumentException if {@code array} is empty
  1017.      * @since 3.4 Changed signature from min(byte[]) to min(byte...)
  1018.      */
  1019.     public static byte min(final byte... array) {
  1020.         // Validates input
  1021.         validateArray(array);
  1022.         // Finds and returns min
  1023.         byte min = array[0];
  1024.         for (int i = 1; i < array.length; i++) {
  1025.             if (array[i] < min) {
  1026.                 min = array[i];
  1027.             }
  1028.         }
  1029.         return min;
  1030.     }

  1031.     /**
  1032.      * Gets the minimum of three {@code byte} values.
  1033.      *
  1034.      * @param a  value 1
  1035.      * @param b  value 2
  1036.      * @param c  value 3
  1037.      * @return  the smallest of the values
  1038.      */
  1039.     public static byte min(byte a, final byte b, final byte c) {
  1040.         if (b < a) {
  1041.             a = b;
  1042.         }
  1043.         if (c < a) {
  1044.             a = c;
  1045.         }
  1046.         return a;
  1047.     }

  1048.     /**
  1049.      * Returns the minimum value in an array.
  1050.      *
  1051.      * @param array  an array, must not be null or empty
  1052.      * @return the minimum value in the array
  1053.      * @throws NullPointerException if {@code array} is {@code null}
  1054.      * @throws IllegalArgumentException if {@code array} is empty
  1055.      * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
  1056.      * @since 3.4 Changed signature from min(double[]) to min(double...)
  1057.      */
  1058.     public static double min(final double... array) {
  1059.         // Validates input
  1060.         validateArray(array);

  1061.         // Finds and returns min
  1062.         double min = array[0];
  1063.         for (int i = 1; i < array.length; i++) {
  1064.             if (Double.isNaN(array[i])) {
  1065.                 return Double.NaN;
  1066.             }
  1067.             if (array[i] < min) {
  1068.                 min = array[i];
  1069.             }
  1070.         }
  1071.         return min;
  1072.     }

  1073.     /**
  1074.      * Gets the minimum of three {@code double} values.
  1075.      *
  1076.      * <p>If any value is {@code NaN}, {@code NaN} is
  1077.      * returned. Infinity is handled.</p>
  1078.      *
  1079.      * @param a  value 1
  1080.      * @param b  value 2
  1081.      * @param c  value 3
  1082.      * @return  the smallest of the values
  1083.      * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently
  1084.      */
  1085.     public static double min(final double a, final double b, final double c) {
  1086.         return Math.min(Math.min(a, b), c);
  1087.     }

  1088.     /**
  1089.      * Returns the minimum value in an array.
  1090.      *
  1091.      * @param array  an array, must not be null or empty
  1092.      * @return the minimum value in the array
  1093.      * @throws NullPointerException if {@code array} is {@code null}
  1094.      * @throws IllegalArgumentException if {@code array} is empty
  1095.      * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
  1096.      * @since 3.4 Changed signature from min(float[]) to min(float...)
  1097.      */
  1098.     public static float min(final float... array) {
  1099.         // Validates input
  1100.         validateArray(array);

  1101.         // Finds and returns min
  1102.         float min = array[0];
  1103.         for (int i = 1; i < array.length; i++) {
  1104.             if (Float.isNaN(array[i])) {
  1105.                 return Float.NaN;
  1106.             }
  1107.             if (array[i] < min) {
  1108.                 min = array[i];
  1109.             }
  1110.         }
  1111.         return min;
  1112.     }

  1113.     /**
  1114.      * Gets the minimum of three {@code float} values.
  1115.      *
  1116.      * <p>If any value is {@code NaN}, {@code NaN} is
  1117.      * returned. Infinity is handled.</p>
  1118.      *
  1119.      * @param a  value 1
  1120.      * @param b  value 2
  1121.      * @param c  value 3
  1122.      * @return  the smallest of the values
  1123.      * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently
  1124.      */
  1125.     public static float min(final float a, final float b, final float c) {
  1126.         return Math.min(Math.min(a, b), c);
  1127.     }

  1128.     /**
  1129.      * Returns the minimum value in an array.
  1130.      *
  1131.      * @param array  an array, must not be null or empty
  1132.      * @return the minimum value in the array
  1133.      * @throws NullPointerException if {@code array} is {@code null}
  1134.      * @throws IllegalArgumentException if {@code array} is empty
  1135.      * @since 3.4 Changed signature from min(int[]) to min(int...)
  1136.      */
  1137.     public static int min(final int... array) {
  1138.         // Validates input
  1139.         validateArray(array);
  1140.         // Finds and returns min
  1141.         int min = array[0];
  1142.         for (int j = 1; j < array.length; j++) {
  1143.             if (array[j] < min) {
  1144.                 min = array[j];
  1145.             }
  1146.         }
  1147.         return min;
  1148.     }

  1149.      /**
  1150.      * Gets the minimum of three {@code int} values.
  1151.      *
  1152.      * @param a  value 1
  1153.      * @param b  value 2
  1154.      * @param c  value 3
  1155.      * @return  the smallest of the values
  1156.      */
  1157.     public static int min(int a, final int b, final int c) {
  1158.         if (b < a) {
  1159.             a = b;
  1160.         }
  1161.         if (c < a) {
  1162.             a = c;
  1163.         }
  1164.         return a;
  1165.     }

  1166.     /**
  1167.      * Returns the minimum value in an array.
  1168.      *
  1169.      * @param array  an array, must not be null or empty
  1170.      * @return the minimum value in the array
  1171.      * @throws NullPointerException if {@code array} is {@code null}
  1172.      * @throws IllegalArgumentException if {@code array} is empty
  1173.      * @since 3.4 Changed signature from min(long[]) to min(long...)
  1174.      */
  1175.     public static long min(final long... array) {
  1176.         // Validates input
  1177.         validateArray(array);
  1178.         // Finds and returns min
  1179.         long min = array[0];
  1180.         for (int i = 1; i < array.length; i++) {
  1181.             if (array[i] < min) {
  1182.                 min = array[i];
  1183.             }
  1184.         }
  1185.         return min;
  1186.     }

  1187.     // 3 param min
  1188.     /**
  1189.      * Gets the minimum of three {@code long} values.
  1190.      *
  1191.      * @param a  value 1
  1192.      * @param b  value 2
  1193.      * @param c  value 3
  1194.      * @return  the smallest of the values
  1195.      */
  1196.     public static long min(long a, final long b, final long c) {
  1197.         if (b < a) {
  1198.             a = b;
  1199.         }
  1200.         if (c < a) {
  1201.             a = c;
  1202.         }
  1203.         return a;
  1204.     }

  1205.     /**
  1206.      * Returns the minimum value in an array.
  1207.      *
  1208.      * @param array  an array, must not be null or empty
  1209.      * @return the minimum value in the array
  1210.      * @throws NullPointerException if {@code array} is {@code null}
  1211.      * @throws IllegalArgumentException if {@code array} is empty
  1212.      * @since 3.4 Changed signature from min(short[]) to min(short...)
  1213.      */
  1214.     public static short min(final short... array) {
  1215.         // Validates input
  1216.         validateArray(array);
  1217.         // Finds and returns min
  1218.         short min = array[0];
  1219.         for (int i = 1; i < array.length; i++) {
  1220.             if (array[i] < min) {
  1221.                 min = array[i];
  1222.             }
  1223.         }

  1224.         return min;
  1225.     }

  1226.     /**
  1227.      * Gets the minimum of three {@code short} values.
  1228.      *
  1229.      * @param a  value 1
  1230.      * @param b  value 2
  1231.      * @param c  value 3
  1232.      * @return  the smallest of the values
  1233.      */
  1234.     public static short min(short a, final short b, final short c) {
  1235.         if (b < a) {
  1236.             a = b;
  1237.         }
  1238.         if (c < a) {
  1239.             a = c;
  1240.         }
  1241.         return a;
  1242.     }

  1243.     /**
  1244.      * Converts a {@link String} to a {@code byte}, returning
  1245.      * {@code zero} if the conversion fails.
  1246.      *
  1247.      * <p>If the string is {@code null}, {@code zero} is returned.</p>
  1248.      *
  1249.      * <pre>
  1250.      *   NumberUtils.toByte(null) = 0
  1251.      *   NumberUtils.toByte("")   = 0
  1252.      *   NumberUtils.toByte("1")  = 1
  1253.      * </pre>
  1254.      *
  1255.      * @param str  the string to convert, may be null
  1256.      * @return the byte represented by the string, or {@code zero} if
  1257.      *  conversion fails
  1258.      * @since 2.5
  1259.      */
  1260.     public static byte toByte(final String str) {
  1261.         return toByte(str, (byte) 0);
  1262.     }

  1263.     /**
  1264.      * Converts a {@link String} to a {@code byte}, returning a
  1265.      * default value if the conversion fails.
  1266.      *
  1267.      * <p>If the string is {@code null}, the default value is returned.</p>
  1268.      *
  1269.      * <pre>
  1270.      *   NumberUtils.toByte(null, 1) = 1
  1271.      *   NumberUtils.toByte("", 1)   = 1
  1272.      *   NumberUtils.toByte("1", 0)  = 1
  1273.      * </pre>
  1274.      *
  1275.      * @param str  the string to convert, may be null
  1276.      * @param defaultValue  the default value
  1277.      * @return the byte represented by the string, or the default if conversion fails
  1278.      * @since 2.5
  1279.      */
  1280.     public static byte toByte(final String str, final byte defaultValue) {
  1281.         try {
  1282.             return Byte.parseByte(str);
  1283.         } catch (final RuntimeException e) {
  1284.             return defaultValue;
  1285.         }
  1286.     }

  1287.     /**
  1288.      * Converts a {@link BigDecimal} to a {@code double}.
  1289.      *
  1290.      * <p>If the {@link BigDecimal} {@code value} is
  1291.      * {@code null}, then the specified default value is returned.</p>
  1292.      *
  1293.      * <pre>
  1294.      *   NumberUtils.toDouble(null)                     = 0.0d
  1295.      *   NumberUtils.toDouble(BigDecimal.valueOf(8.5d)) = 8.5d
  1296.      * </pre>
  1297.      *
  1298.      * @param value the {@link BigDecimal} to convert, may be {@code null}.
  1299.      * @return the double represented by the {@link BigDecimal} or
  1300.      *  {@code 0.0d} if the {@link BigDecimal} is {@code null}.
  1301.      * @since 3.8
  1302.      */
  1303.     public static double toDouble(final BigDecimal value) {
  1304.         return toDouble(value, 0.0d);
  1305.     }

  1306.     /**
  1307.      * Converts a {@link BigDecimal} to a {@code double}.
  1308.      *
  1309.      * <p>If the {@link BigDecimal} {@code value} is
  1310.      * {@code null}, then the specified default value is returned.</p>
  1311.      *
  1312.      * <pre>
  1313.      *   NumberUtils.toDouble(null, 1.1d)                     = 1.1d
  1314.      *   NumberUtils.toDouble(BigDecimal.valueOf(8.5d), 1.1d) = 8.5d
  1315.      * </pre>
  1316.      *
  1317.      * @param value the {@link BigDecimal} to convert, may be {@code null}.
  1318.      * @param defaultValue the default value
  1319.      * @return the double represented by the {@link BigDecimal} or the
  1320.      *  defaultValue if the {@link BigDecimal} is {@code null}.
  1321.      * @since 3.8
  1322.      */
  1323.     public static double toDouble(final BigDecimal value, final double defaultValue) {
  1324.         return value == null ? defaultValue : value.doubleValue();
  1325.     }

  1326.     /**
  1327.      * Converts a {@link String} to a {@code double}, returning
  1328.      * {@code 0.0d} if the conversion fails.
  1329.      *
  1330.      * <p>If the string {@code str} is {@code null},
  1331.      * {@code 0.0d} is returned.</p>
  1332.      *
  1333.      * <pre>
  1334.      *   NumberUtils.toDouble(null)   = 0.0d
  1335.      *   NumberUtils.toDouble("")     = 0.0d
  1336.      *   NumberUtils.toDouble("1.5")  = 1.5d
  1337.      * </pre>
  1338.      *
  1339.      * @param str the string to convert, may be {@code null}
  1340.      * @return the double represented by the string, or {@code 0.0d}
  1341.      *  if conversion fails
  1342.      * @since 2.1
  1343.      */
  1344.     public static double toDouble(final String str) {
  1345.         return toDouble(str, 0.0d);
  1346.     }

  1347.     /**
  1348.      * Converts a {@link String} to a {@code double}, returning a
  1349.      * default value if the conversion fails.
  1350.      *
  1351.      * <p>If the string {@code str} is {@code null}, the default
  1352.      * value is returned.</p>
  1353.      *
  1354.      * <pre>
  1355.      *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
  1356.      *   NumberUtils.toDouble("", 1.1d)     = 1.1d
  1357.      *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
  1358.      * </pre>
  1359.      *
  1360.      * @param str the string to convert, may be {@code null}
  1361.      * @param defaultValue the default value
  1362.      * @return the double represented by the string, or defaultValue
  1363.      *  if conversion fails
  1364.      * @since 2.1
  1365.      */
  1366.     public static double toDouble(final String str, final double defaultValue) {
  1367.       try {
  1368.           return Double.parseDouble(str);
  1369.       } catch (final RuntimeException e) {
  1370.           return defaultValue;
  1371.       }
  1372.     }

  1373.     /**
  1374.      * Converts a {@link String} to a {@code float}, returning
  1375.      * {@code 0.0f} if the conversion fails.
  1376.      *
  1377.      * <p>If the string {@code str} is {@code null},
  1378.      * {@code 0.0f} is returned.</p>
  1379.      *
  1380.      * <pre>
  1381.      *   NumberUtils.toFloat(null)   = 0.0f
  1382.      *   NumberUtils.toFloat("")     = 0.0f
  1383.      *   NumberUtils.toFloat("1.5")  = 1.5f
  1384.      * </pre>
  1385.      *
  1386.      * @param str the string to convert, may be {@code null}
  1387.      * @return the float represented by the string, or {@code 0.0f}
  1388.      *  if conversion fails
  1389.      * @since 2.1
  1390.      */
  1391.     public static float toFloat(final String str) {
  1392.         return toFloat(str, 0.0f);
  1393.     }

  1394.     /**
  1395.      * Converts a {@link String} to a {@code float}, returning a
  1396.      * default value if the conversion fails.
  1397.      *
  1398.      * <p>If the string {@code str} is {@code null}, the default
  1399.      * value is returned.</p>
  1400.      *
  1401.      * <pre>
  1402.      *   NumberUtils.toFloat(null, 1.1f)   = 1.1f
  1403.      *   NumberUtils.toFloat("", 1.1f)     = 1.1f
  1404.      *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
  1405.      * </pre>
  1406.      *
  1407.      * @param str the string to convert, may be {@code null}
  1408.      * @param defaultValue the default value
  1409.      * @return the float represented by the string, or defaultValue
  1410.      *  if conversion fails
  1411.      * @since 2.1
  1412.      */
  1413.     public static float toFloat(final String str, final float defaultValue) {
  1414.       try {
  1415.           return Float.parseFloat(str);
  1416.       } catch (final RuntimeException e) {
  1417.           return defaultValue;
  1418.       }
  1419.     }

  1420.     /**
  1421.      * Converts a {@link String} to an {@code int}, returning
  1422.      * {@code zero} if the conversion fails.
  1423.      *
  1424.      * <p>If the string is {@code null}, {@code zero} is returned.</p>
  1425.      *
  1426.      * <pre>
  1427.      *   NumberUtils.toInt(null) = 0
  1428.      *   NumberUtils.toInt("")   = 0
  1429.      *   NumberUtils.toInt("1")  = 1
  1430.      * </pre>
  1431.      *
  1432.      * @param str  the string to convert, may be null
  1433.      * @return the int represented by the string, or {@code zero} if
  1434.      *  conversion fails
  1435.      * @since 2.1
  1436.      */
  1437.     public static int toInt(final String str) {
  1438.         return toInt(str, 0);
  1439.     }

  1440.     /**
  1441.      * Converts a {@link String} to an {@code int}, returning a
  1442.      * default value if the conversion fails.
  1443.      *
  1444.      * <p>If the string is {@code null}, the default value is returned.</p>
  1445.      *
  1446.      * <pre>
  1447.      *   NumberUtils.toInt(null, 1) = 1
  1448.      *   NumberUtils.toInt("", 1)   = 1
  1449.      *   NumberUtils.toInt("1", 0)  = 1
  1450.      * </pre>
  1451.      *
  1452.      * @param str  the string to convert, may be null
  1453.      * @param defaultValue  the default value
  1454.      * @return the int represented by the string, or the default if conversion fails
  1455.      * @since 2.1
  1456.      */
  1457.     public static int toInt(final String str, final int defaultValue) {
  1458.         try {
  1459.             return Integer.parseInt(str);
  1460.         } catch (final RuntimeException e) {
  1461.             return defaultValue;
  1462.         }
  1463.     }

  1464.     /**
  1465.      * Converts a {@link String} to a {@code long}, returning
  1466.      * {@code zero} if the conversion fails.
  1467.      *
  1468.      * <p>If the string is {@code null}, {@code zero} is returned.</p>
  1469.      *
  1470.      * <pre>
  1471.      *   NumberUtils.toLong(null) = 0L
  1472.      *   NumberUtils.toLong("")   = 0L
  1473.      *   NumberUtils.toLong("1")  = 1L
  1474.      * </pre>
  1475.      *
  1476.      * @param str  the string to convert, may be null
  1477.      * @return the long represented by the string, or {@code 0} if
  1478.      *  conversion fails
  1479.      * @since 2.1
  1480.      */
  1481.     public static long toLong(final String str) {
  1482.         return toLong(str, 0L);
  1483.     }

  1484.     /**
  1485.      * Converts a {@link String} to a {@code long}, returning a
  1486.      * default value if the conversion fails.
  1487.      *
  1488.      * <p>If the string is {@code null}, the default value is returned.</p>
  1489.      *
  1490.      * <pre>
  1491.      *   NumberUtils.toLong(null, 1L) = 1L
  1492.      *   NumberUtils.toLong("", 1L)   = 1L
  1493.      *   NumberUtils.toLong("1", 0L)  = 1L
  1494.      * </pre>
  1495.      *
  1496.      * @param str  the string to convert, may be null
  1497.      * @param defaultValue  the default value
  1498.      * @return the long represented by the string, or the default if conversion fails
  1499.      * @since 2.1
  1500.      */
  1501.     public static long toLong(final String str, final long defaultValue) {
  1502.         try {
  1503.             return Long.parseLong(str);
  1504.         } catch (final RuntimeException e) {
  1505.             return defaultValue;
  1506.         }
  1507.     }

  1508.     /**
  1509.      * Converts a {@link BigDecimal} to a {@link BigDecimal} with a scale of
  1510.      * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
  1511.      * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
  1512.      *
  1513.      * <p>Note, the scale of a {@link BigDecimal} is the number of digits to the right of the
  1514.      * decimal point.</p>
  1515.      *
  1516.      * @param value the {@link BigDecimal} to convert, may be null.
  1517.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1518.      * @since 3.8
  1519.      */
  1520.     public static BigDecimal toScaledBigDecimal(final BigDecimal value) {
  1521.         return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
  1522.     }

  1523.     /**
  1524.      * Converts a {@link BigDecimal} to a {@link BigDecimal} whose scale is the
  1525.      * specified value with a {@link RoundingMode} applied. If the input {@code value}
  1526.      * is {@code null}, we simply return {@code BigDecimal.ZERO}.
  1527.      *
  1528.      * @param value the {@link BigDecimal} to convert, may be null.
  1529.      * @param scale the number of digits to the right of the decimal point.
  1530.      * @param roundingMode a rounding behavior for numerical operations capable of
  1531.      *  discarding precision.
  1532.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1533.      * @since 3.8
  1534.      */
  1535.     public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, final RoundingMode roundingMode) {
  1536.         if (value == null) {
  1537.             return BigDecimal.ZERO;
  1538.         }
  1539.         return value.setScale(
  1540.             scale,
  1541.             roundingMode == null ? RoundingMode.HALF_EVEN : roundingMode
  1542.         );
  1543.     }

  1544.     /**
  1545.      * Converts a {@link Double} to a {@link BigDecimal} with a scale of
  1546.      * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
  1547.      * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
  1548.      *
  1549.      * <p>Note, the scale of a {@link BigDecimal} is the number of digits to the right of the
  1550.      * decimal point.</p>
  1551.      *
  1552.      * @param value the {@link Double} to convert, may be null.
  1553.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1554.      * @since 3.8
  1555.      */
  1556.     public static BigDecimal toScaledBigDecimal(final Double value) {
  1557.         return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
  1558.     }

  1559.     /**
  1560.      * Converts a {@link Double} to a {@link BigDecimal} whose scale is the
  1561.      * specified value with a {@link RoundingMode} applied. If the input {@code value}
  1562.      * is {@code null}, we simply return {@code BigDecimal.ZERO}.
  1563.      *
  1564.      * @param value the {@link Double} to convert, may be null.
  1565.      * @param scale the number of digits to the right of the decimal point.
  1566.      * @param roundingMode a rounding behavior for numerical operations capable of
  1567.      *  discarding precision.
  1568.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1569.      * @since 3.8
  1570.      */
  1571.     public static BigDecimal toScaledBigDecimal(final Double value, final int scale, final RoundingMode roundingMode) {
  1572.         if (value == null) {
  1573.             return BigDecimal.ZERO;
  1574.         }
  1575.         return toScaledBigDecimal(
  1576.             BigDecimal.valueOf(value),
  1577.             scale,
  1578.             roundingMode
  1579.         );
  1580.     }

  1581.     /**
  1582.      * Converts a {@link Float} to a {@link BigDecimal} with a scale of
  1583.      * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
  1584.      * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
  1585.      *
  1586.      * <p>Note, the scale of a {@link BigDecimal} is the number of digits to the right of the
  1587.      * decimal point.</p>
  1588.      *
  1589.      * @param value the {@link Float} to convert, may be null.
  1590.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1591.      * @since 3.8
  1592.      */
  1593.     public static BigDecimal toScaledBigDecimal(final Float value) {
  1594.         return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
  1595.     }

  1596.     /**
  1597.      * Converts a {@link Float} to a {@link BigDecimal} whose scale is the
  1598.      * specified value with a {@link RoundingMode} applied. If the input {@code value}
  1599.      * is {@code null}, we simply return {@code BigDecimal.ZERO}.
  1600.      *
  1601.      * @param value the {@link Float} to convert, may be null.
  1602.      * @param scale the number of digits to the right of the decimal point.
  1603.      * @param roundingMode a rounding behavior for numerical operations capable of
  1604.      *  discarding precision.
  1605.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1606.      * @since 3.8
  1607.      */
  1608.     public static BigDecimal toScaledBigDecimal(final Float value, final int scale, final RoundingMode roundingMode) {
  1609.         if (value == null) {
  1610.             return BigDecimal.ZERO;
  1611.         }
  1612.         return toScaledBigDecimal(
  1613.             BigDecimal.valueOf(value),
  1614.             scale,
  1615.             roundingMode
  1616.         );
  1617.     }

  1618.     /**
  1619.      * Converts a {@link String} to a {@link BigDecimal} with a scale of
  1620.      * two that has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied
  1621.      * {@code value} is null, then {@code BigDecimal.ZERO} is returned.
  1622.      *
  1623.      * <p>Note, the scale of a {@link BigDecimal} is the number of digits to the right of the
  1624.      * decimal point.</p>
  1625.      *
  1626.      * @param value the {@link String} to convert, may be null.
  1627.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1628.      * @since 3.8
  1629.      */
  1630.     public static BigDecimal toScaledBigDecimal(final String value) {
  1631.         return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
  1632.     }

  1633.     /**
  1634.      * Converts a {@link String} to a {@link BigDecimal} whose scale is the
  1635.      * specified value with a {@link RoundingMode} applied. If the input {@code value}
  1636.      * is {@code null}, we simply return {@code BigDecimal.ZERO}.
  1637.      *
  1638.      * @param value the {@link String} to convert, may be null.
  1639.      * @param scale the number of digits to the right of the decimal point.
  1640.      * @param roundingMode a rounding behavior for numerical operations capable of
  1641.      *  discarding precision.
  1642.      * @return the scaled, with appropriate rounding, {@link BigDecimal}.
  1643.      * @since 3.8
  1644.      */
  1645.     public static BigDecimal toScaledBigDecimal(final String value, final int scale, final RoundingMode roundingMode) {
  1646.         if (value == null) {
  1647.             return BigDecimal.ZERO;
  1648.         }
  1649.         return toScaledBigDecimal(
  1650.             createBigDecimal(value),
  1651.             scale,
  1652.             roundingMode
  1653.         );
  1654.     }

  1655.     /**
  1656.      * Converts a {@link String} to a {@code short}, returning
  1657.      * {@code zero} if the conversion fails.
  1658.      *
  1659.      * <p>If the string is {@code null}, {@code zero} is returned.</p>
  1660.      *
  1661.      * <pre>
  1662.      *   NumberUtils.toShort(null) = 0
  1663.      *   NumberUtils.toShort("")   = 0
  1664.      *   NumberUtils.toShort("1")  = 1
  1665.      * </pre>
  1666.      *
  1667.      * @param str  the string to convert, may be null
  1668.      * @return the short represented by the string, or {@code zero} if
  1669.      *  conversion fails
  1670.      * @since 2.5
  1671.      */
  1672.     public static short toShort(final String str) {
  1673.         return toShort(str, (short) 0);
  1674.     }

  1675.     /**
  1676.      * Converts a {@link String} to an {@code short}, returning a
  1677.      * default value if the conversion fails.
  1678.      *
  1679.      * <p>If the string is {@code null}, the default value is returned.</p>
  1680.      *
  1681.      * <pre>
  1682.      *   NumberUtils.toShort(null, 1) = 1
  1683.      *   NumberUtils.toShort("", 1)   = 1
  1684.      *   NumberUtils.toShort("1", 0)  = 1
  1685.      * </pre>
  1686.      *
  1687.      * @param str  the string to convert, may be null
  1688.      * @param defaultValue  the default value
  1689.      * @return the short represented by the string, or the default if conversion fails
  1690.      * @since 2.5
  1691.      */
  1692.     public static short toShort(final String str, final short defaultValue) {
  1693.         try {
  1694.             return Short.parseShort(str);
  1695.         } catch (final RuntimeException e) {
  1696.             return defaultValue;
  1697.         }
  1698.     }

  1699.     /**
  1700.      * Checks if the specified array is neither null nor empty.
  1701.      *
  1702.      * @param array  the array to check
  1703.      * @throws IllegalArgumentException if {@code array} is empty
  1704.      * @throws NullPointerException if {@code array} is {@code null}
  1705.      */
  1706.     private static void validateArray(final Object array) {
  1707.         Objects.requireNonNull(array, "array");
  1708.         Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");
  1709.     }

  1710.     private static boolean withDecimalsParsing(final String str, final int beginIdx) {
  1711.         int decimalPoints = 0;
  1712.         for (int i = beginIdx; i < str.length(); i++) {
  1713.             final char ch = str.charAt(i);
  1714.             final boolean isDecimalPoint = ch == '.';
  1715.             if (isDecimalPoint) {
  1716.                 decimalPoints++;
  1717.             }
  1718.             if (decimalPoints > 1) {
  1719.                 return false;
  1720.             }
  1721.             if (!isDecimalPoint && !Character.isDigit(ch)) {
  1722.                 return false;
  1723.             }
  1724.         }
  1725.         return true;
  1726.     }

  1727.     /**
  1728.      * {@link NumberUtils} instances should NOT be constructed in standard programming.
  1729.      * Instead, the class should be used as {@code NumberUtils.toInt("6");}.
  1730.      *
  1731.      * <p>This constructor is public to permit tools that require a JavaBean instance
  1732.      * to operate.</p>
  1733.      *
  1734.      * @deprecated TODO Make private in 4.0.
  1735.      */
  1736.     @Deprecated
  1737.     public NumberUtils() {
  1738.         // empty
  1739.     }
  1740. }