Debian Codegraph @

src/org/apache/commons/lang3/math/NumberUtils.java

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