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