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