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