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