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