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.  *      https://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.CharUtils;
  24. import org.apache.commons.lang3.StringUtils;
  25. import org.apache.commons.lang3.Validate;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  713.     private static boolean isSign(final char ch) {
  714.         return ch == '-' || ch == '+';
  715.      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  1226.         return min;
  1227.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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