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