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