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; 022 023import org.apache.commons.lang3.StringUtils; 024 025/** 026 * <p>Provides extra functionality for Java Number classes.</p> 027 * 028 * @since 2.0 029 * @version $Id: NumberUtils.java 1582585 2014-03-28 03:10:27Z niallp $ 030 */ 031public class NumberUtils { 032 033 /** Reusable Long constant for zero. */ 034 public static final Long LONG_ZERO = Long.valueOf(0L); 035 /** Reusable Long constant for one. */ 036 public static final Long LONG_ONE = Long.valueOf(1L); 037 /** Reusable Long constant for minus one. */ 038 public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); 039 /** Reusable Integer constant for zero. */ 040 public static final Integer INTEGER_ZERO = Integer.valueOf(0); 041 /** Reusable Integer constant for one. */ 042 public static final Integer INTEGER_ONE = Integer.valueOf(1); 043 /** Reusable Integer constant for minus one. */ 044 public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); 045 /** Reusable Short constant for zero. */ 046 public static final Short SHORT_ZERO = Short.valueOf((short) 0); 047 /** Reusable Short constant for one. */ 048 public static final Short SHORT_ONE = Short.valueOf((short) 1); 049 /** Reusable Short constant for minus one. */ 050 public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); 051 /** Reusable Byte constant for zero. */ 052 public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); 053 /** Reusable Byte constant for one. */ 054 public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); 055 /** Reusable Byte constant for minus one. */ 056 public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); 057 /** Reusable Double constant for zero. */ 058 public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); 059 /** Reusable Double constant for one. */ 060 public static final Double DOUBLE_ONE = Double.valueOf(1.0d); 061 /** Reusable Double constant for minus one. */ 062 public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); 063 /** Reusable Float constant for zero. */ 064 public static final Float FLOAT_ZERO = Float.valueOf(0.0f); 065 /** Reusable Float constant for one. */ 066 public static final Float FLOAT_ONE = Float.valueOf(1.0f); 067 /** Reusable Float constant for minus one. */ 068 public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); 069 070 /** 071 * <p><code>NumberUtils</code> instances should NOT be constructed in standard programming. 072 * Instead, the class should be used as <code>NumberUtils.toInt("6");</code>.</p> 073 * 074 * <p>This constructor is public to permit tools that require a JavaBean instance 075 * to operate.</p> 076 */ 077 public NumberUtils() { 078 super(); 079 } 080 081 //----------------------------------------------------------------------- 082 /** 083 * <p>Convert a <code>String</code> to an <code>int</code>, returning 084 * <code>zero</code> if the conversion fails.</p> 085 * 086 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p> 087 * 088 * <pre> 089 * NumberUtils.toInt(null) = 0 090 * NumberUtils.toInt("") = 0 091 * NumberUtils.toInt("1") = 1 092 * </pre> 093 * 094 * @param str the string to convert, may be null 095 * @return the int represented by the string, or <code>zero</code> if 096 * conversion fails 097 * @since 2.1 098 */ 099 public static int toInt(final String str) { 100 return toInt(str, 0); 101 } 102 103 /** 104 * <p>Convert a <code>String</code> to an <code>int</code>, returning a 105 * default value if the conversion fails.</p> 106 * 107 * <p>If the string is <code>null</code>, the default value is returned.</p> 108 * 109 * <pre> 110 * NumberUtils.toInt(null, 1) = 1 111 * NumberUtils.toInt("", 1) = 1 112 * NumberUtils.toInt("1", 0) = 1 113 * </pre> 114 * 115 * @param str the string to convert, may be null 116 * @param defaultValue the default value 117 * @return the int represented by the string, or the default if conversion fails 118 * @since 2.1 119 */ 120 public static int toInt(final String str, final int defaultValue) { 121 if(str == null) { 122 return defaultValue; 123 } 124 try { 125 return Integer.parseInt(str); 126 } catch (final NumberFormatException nfe) { 127 return defaultValue; 128 } 129 } 130 131 /** 132 * <p>Convert a <code>String</code> to a <code>long</code>, returning 133 * <code>zero</code> if the conversion fails.</p> 134 * 135 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p> 136 * 137 * <pre> 138 * NumberUtils.toLong(null) = 0L 139 * NumberUtils.toLong("") = 0L 140 * NumberUtils.toLong("1") = 1L 141 * </pre> 142 * 143 * @param str the string to convert, may be null 144 * @return the long represented by the string, or <code>0</code> if 145 * conversion fails 146 * @since 2.1 147 */ 148 public static long toLong(final String str) { 149 return toLong(str, 0L); 150 } 151 152 /** 153 * <p>Convert a <code>String</code> to a <code>long</code>, returning a 154 * default value if the conversion fails.</p> 155 * 156 * <p>If the string is <code>null</code>, the default value is returned.</p> 157 * 158 * <pre> 159 * NumberUtils.toLong(null, 1L) = 1L 160 * NumberUtils.toLong("", 1L) = 1L 161 * NumberUtils.toLong("1", 0L) = 1L 162 * </pre> 163 * 164 * @param str the string to convert, may be null 165 * @param defaultValue the default value 166 * @return the long represented by the string, or the default if conversion fails 167 * @since 2.1 168 */ 169 public static long toLong(final String str, final long defaultValue) { 170 if (str == null) { 171 return defaultValue; 172 } 173 try { 174 return Long.parseLong(str); 175 } catch (final NumberFormatException nfe) { 176 return defaultValue; 177 } 178 } 179 180 /** 181 * <p>Convert a <code>String</code> to a <code>float</code>, returning 182 * <code>0.0f</code> if the conversion fails.</p> 183 * 184 * <p>If the string <code>str</code> is <code>null</code>, 185 * <code>0.0f</code> is returned.</p> 186 * 187 * <pre> 188 * NumberUtils.toFloat(null) = 0.0f 189 * NumberUtils.toFloat("") = 0.0f 190 * NumberUtils.toFloat("1.5") = 1.5f 191 * </pre> 192 * 193 * @param str the string to convert, may be <code>null</code> 194 * @return the float represented by the string, or <code>0.0f</code> 195 * if conversion fails 196 * @since 2.1 197 */ 198 public static float toFloat(final String str) { 199 return toFloat(str, 0.0f); 200 } 201 202 /** 203 * <p>Convert a <code>String</code> to a <code>float</code>, returning a 204 * default value if the conversion fails.</p> 205 * 206 * <p>If the string <code>str</code> is <code>null</code>, the default 207 * value is returned.</p> 208 * 209 * <pre> 210 * NumberUtils.toFloat(null, 1.1f) = 1.0f 211 * NumberUtils.toFloat("", 1.1f) = 1.1f 212 * NumberUtils.toFloat("1.5", 0.0f) = 1.5f 213 * </pre> 214 * 215 * @param str the string to convert, may be <code>null</code> 216 * @param defaultValue the default value 217 * @return the float represented by the string, or defaultValue 218 * if conversion fails 219 * @since 2.1 220 */ 221 public static float toFloat(final String str, final float defaultValue) { 222 if (str == null) { 223 return defaultValue; 224 } 225 try { 226 return Float.parseFloat(str); 227 } catch (final NumberFormatException nfe) { 228 return defaultValue; 229 } 230 } 231 232 /** 233 * <p>Convert a <code>String</code> to a <code>double</code>, returning 234 * <code>0.0d</code> if the conversion fails.</p> 235 * 236 * <p>If the string <code>str</code> is <code>null</code>, 237 * <code>0.0d</code> is returned.</p> 238 * 239 * <pre> 240 * NumberUtils.toDouble(null) = 0.0d 241 * NumberUtils.toDouble("") = 0.0d 242 * NumberUtils.toDouble("1.5") = 1.5d 243 * </pre> 244 * 245 * @param str the string to convert, may be <code>null</code> 246 * @return the double represented by the string, or <code>0.0d</code> 247 * if conversion fails 248 * @since 2.1 249 */ 250 public static double toDouble(final String str) { 251 return toDouble(str, 0.0d); 252 } 253 254 /** 255 * <p>Convert a <code>String</code> to a <code>double</code>, returning a 256 * default value if the conversion fails.</p> 257 * 258 * <p>If the string <code>str</code> is <code>null</code>, the default 259 * value is returned.</p> 260 * 261 * <pre> 262 * NumberUtils.toDouble(null, 1.1d) = 1.1d 263 * NumberUtils.toDouble("", 1.1d) = 1.1d 264 * NumberUtils.toDouble("1.5", 0.0d) = 1.5d 265 * </pre> 266 * 267 * @param str the string to convert, may be <code>null</code> 268 * @param defaultValue the default value 269 * @return the double represented by the string, or defaultValue 270 * if conversion fails 271 * @since 2.1 272 */ 273 public static double toDouble(final String str, final double defaultValue) { 274 if (str == null) { 275 return defaultValue; 276 } 277 try { 278 return Double.parseDouble(str); 279 } catch (final NumberFormatException nfe) { 280 return defaultValue; 281 } 282 } 283 284 //----------------------------------------------------------------------- 285 /** 286 * <p>Convert a <code>String</code> to a <code>byte</code>, returning 287 * <code>zero</code> if the conversion fails.</p> 288 * 289 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p> 290 * 291 * <pre> 292 * NumberUtils.toByte(null) = 0 293 * NumberUtils.toByte("") = 0 294 * NumberUtils.toByte("1") = 1 295 * </pre> 296 * 297 * @param str the string to convert, may be null 298 * @return the byte represented by the string, or <code>zero</code> if 299 * conversion fails 300 * @since 2.5 301 */ 302 public static byte toByte(final String str) { 303 return toByte(str, (byte) 0); 304 } 305 306 /** 307 * <p>Convert a <code>String</code> to a <code>byte</code>, returning a 308 * default value if the conversion fails.</p> 309 * 310 * <p>If the string is <code>null</code>, the default value is returned.</p> 311 * 312 * <pre> 313 * NumberUtils.toByte(null, 1) = 1 314 * NumberUtils.toByte("", 1) = 1 315 * NumberUtils.toByte("1", 0) = 1 316 * </pre> 317 * 318 * @param str the string to convert, may be null 319 * @param defaultValue the default value 320 * @return the byte represented by the string, or the default if conversion fails 321 * @since 2.5 322 */ 323 public static byte toByte(final String str, final byte defaultValue) { 324 if(str == null) { 325 return defaultValue; 326 } 327 try { 328 return Byte.parseByte(str); 329 } catch (final NumberFormatException nfe) { 330 return defaultValue; 331 } 332 } 333 334 /** 335 * <p>Convert a <code>String</code> to a <code>short</code>, returning 336 * <code>zero</code> if the conversion fails.</p> 337 * 338 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p> 339 * 340 * <pre> 341 * NumberUtils.toShort(null) = 0 342 * NumberUtils.toShort("") = 0 343 * NumberUtils.toShort("1") = 1 344 * </pre> 345 * 346 * @param str the string to convert, may be null 347 * @return the short represented by the string, or <code>zero</code> if 348 * conversion fails 349 * @since 2.5 350 */ 351 public static short toShort(final String str) { 352 return toShort(str, (short) 0); 353 } 354 355 /** 356 * <p>Convert a <code>String</code> to an <code>short</code>, returning a 357 * default value if the conversion fails.</p> 358 * 359 * <p>If the string is <code>null</code>, the default value is returned.</p> 360 * 361 * <pre> 362 * NumberUtils.toShort(null, 1) = 1 363 * NumberUtils.toShort("", 1) = 1 364 * NumberUtils.toShort("1", 0) = 1 365 * </pre> 366 * 367 * @param str the string to convert, may be null 368 * @param defaultValue the default value 369 * @return the short represented by the string, or the default if conversion fails 370 * @since 2.5 371 */ 372 public static short toShort(final String str, final short defaultValue) { 373 if(str == null) { 374 return defaultValue; 375 } 376 try { 377 return Short.parseShort(str); 378 } catch (final NumberFormatException nfe) { 379 return defaultValue; 380 } 381 } 382 383 //----------------------------------------------------------------------- 384 // must handle Long, Float, Integer, Float, Short, 385 // BigDecimal, BigInteger and Byte 386 // useful methods: 387 // Byte.decode(String) 388 // Byte.valueOf(String,int radix) 389 // Byte.valueOf(String) 390 // Double.valueOf(String) 391 // Float.valueOf(String) 392 // Float.valueOf(String) 393 // Integer.valueOf(String,int radix) 394 // Integer.valueOf(String) 395 // Integer.decode(String) 396 // Integer.getInteger(String) 397 // Integer.getInteger(String,int val) 398 // Integer.getInteger(String,Integer val) 399 // Integer.valueOf(String) 400 // Double.valueOf(String) 401 // new Byte(String) 402 // Long.valueOf(String) 403 // Long.getLong(String) 404 // Long.getLong(String,int) 405 // Long.getLong(String,Integer) 406 // Long.valueOf(String,int) 407 // Long.valueOf(String) 408 // Short.valueOf(String) 409 // Short.decode(String) 410 // Short.valueOf(String,int) 411 // Short.valueOf(String) 412 // new BigDecimal(String) 413 // new BigInteger(String) 414 // new BigInteger(String,int radix) 415 // Possible inputs: 416 // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd 417 // plus minus everything. Prolly more. A lot are not separable. 418 419 /** 420 * <p>Turns a string value into a java.lang.Number.</p> 421 * 422 * <p>If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it 423 * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the 424 * prefix is more than 8 - or BigInteger if there are more than 16 digits. 425 * </p> 426 * <p>Then, the value is examined for a type qualifier on the end, i.e. one of 427 * <code>'f','F','d','D','l','L'</code>. If it is found, it starts 428 * trying to create successively larger types from the type specified 429 * until one is found that can represent the value.</p> 430 * 431 * <p>If a type specifier is not found, it will check for a decimal point 432 * and then try successively larger types from <code>Integer</code> to 433 * <code>BigInteger</code> and from <code>Float</code> to 434 * <code>BigDecimal</code>.</p> 435 * 436 * <p> 437 * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will 438 * be Integer, Long or BigDecimal as appropriate. 439 * </p> 440 * 441 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 442 * 443 * <p>This method does not trim the input string, i.e., strings with leading 444 * or trailing spaces will generate NumberFormatExceptions.</p> 445 * 446 * @param str String containing a number, may be null 447 * @return Number created from the string (or null if the input is null) 448 * @throws NumberFormatException if the value cannot be converted 449 */ 450 public static Number createNumber(final String str) throws NumberFormatException { 451 if (str == null) { 452 return null; 453 } 454 if (StringUtils.isBlank(str)) { 455 throw new NumberFormatException("A blank string is not a valid number"); 456 } 457 // Need to deal with all possible hex prefixes here 458 final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; 459 int pfxLen = 0; 460 for(final String pfx : hex_prefixes) { 461 if (str.startsWith(pfx)) { 462 pfxLen += pfx.length(); 463 break; 464 } 465 } 466 if (pfxLen > 0) { // we have a hex number 467 char firstSigDigit = 0; // strip leading zeroes 468 for(int i = pfxLen; i < str.length(); i++) { 469 firstSigDigit = str.charAt(i); 470 if (firstSigDigit == '0') { // count leading zeroes 471 pfxLen++; 472 } else { 473 break; 474 } 475 } 476 final int hexDigits = str.length() - pfxLen; 477 if (hexDigits > 16 || (hexDigits == 16 && firstSigDigit > '7')) { // too many for Long 478 return createBigInteger(str); 479 } 480 if (hexDigits > 8 || (hexDigits == 8 && firstSigDigit > '7')) { // too many for an int 481 return createLong(str); 482 } 483 return createInteger(str); 484 } 485 final char lastChar = str.charAt(str.length() - 1); 486 String mant; 487 String dec; 488 String exp; 489 final int decPos = str.indexOf('.'); 490 final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present 491 // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) 492 // and the parsing which will detect if e or E appear in a number due to using the wrong offset 493 494 int numDecimals = 0; // Check required precision (LANG-693) 495 if (decPos > -1) { // there is a decimal point 496 497 if (expPos > -1) { // there is an exponent 498 if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE 499 throw new NumberFormatException(str + " is not a valid number."); 500 } 501 dec = str.substring(decPos + 1, expPos); 502 } else { 503 dec = str.substring(decPos + 1); 504 } 505 mant = str.substring(0, decPos); 506 numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers. 507 } else { 508 if (expPos > -1) { 509 if (expPos > str.length()) { // prevents double exponent causing IOOBE 510 throw new NumberFormatException(str + " is not a valid number."); 511 } 512 mant = str.substring(0, expPos); 513 } else { 514 mant = str; 515 } 516 dec = null; 517 } 518 if (!Character.isDigit(lastChar) && lastChar != '.') { 519 if (expPos > -1 && expPos < str.length() - 1) { 520 exp = str.substring(expPos + 1, str.length() - 1); 521 } else { 522 exp = null; 523 } 524 //Requesting a specific type.. 525 final String numeric = str.substring(0, str.length() - 1); 526 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); 527 switch (lastChar) { 528 case 'l' : 529 case 'L' : 530 if (dec == null 531 && exp == null 532 && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { 533 try { 534 return createLong(numeric); 535 } catch (final NumberFormatException nfe) { // NOPMD 536 // Too big for a long 537 } 538 return createBigInteger(numeric); 539 540 } 541 throw new NumberFormatException(str + " is not a valid number."); 542 case 'f' : 543 case 'F' : 544 try { 545 final Float f = NumberUtils.createFloat(numeric); 546 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { 547 //If it's too big for a float or the float value = 0 and the string 548 //has non-zeros in it, then float does not have the precision we want 549 return f; 550 } 551 552 } catch (final NumberFormatException nfe) { // NOPMD 553 // ignore the bad number 554 } 555 //$FALL-THROUGH$ 556 case 'd' : 557 case 'D' : 558 try { 559 final Double d = NumberUtils.createDouble(numeric); 560 if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { 561 return d; 562 } 563 } catch (final NumberFormatException nfe) { // NOPMD 564 // ignore the bad number 565 } 566 try { 567 return createBigDecimal(numeric); 568 } catch (final NumberFormatException e) { // NOPMD 569 // ignore the bad number 570 } 571 //$FALL-THROUGH$ 572 default : 573 throw new NumberFormatException(str + " is not a valid number."); 574 575 } 576 } 577 //User doesn't have a preference on the return type, so let's start 578 //small and go from there... 579 if (expPos > -1 && expPos < str.length() - 1) { 580 exp = str.substring(expPos + 1, str.length()); 581 } else { 582 exp = null; 583 } 584 if (dec == null && exp == null) { // no decimal point and no exponent 585 //Must be an Integer, Long, Biginteger 586 try { 587 return createInteger(str); 588 } catch (final NumberFormatException nfe) { // NOPMD 589 // ignore the bad number 590 } 591 try { 592 return createLong(str); 593 } catch (final NumberFormatException nfe) { // NOPMD 594 // ignore the bad number 595 } 596 return createBigInteger(str); 597 } 598 599 //Must be a Float, Double, BigDecimal 600 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); 601 try { 602 if(numDecimals <= 7){// If number has 7 or fewer digits past the decimal point then make it a float 603 final Float f = createFloat(str); 604 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { 605 return f; 606 } 607 } 608 } catch (final NumberFormatException nfe) { // NOPMD 609 // ignore the bad number 610 } 611 try { 612 if(numDecimals <= 16){// If number has between 8 and 16 digits past the decimal point then make it a double 613 final Double d = createDouble(str); 614 if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { 615 return d; 616 } 617 } 618 } catch (final NumberFormatException nfe) { // NOPMD 619 // ignore the bad number 620 } 621 622 return createBigDecimal(str); 623 } 624 625 /** 626 * <p>Utility method for {@link #createNumber(java.lang.String)}.</p> 627 * 628 * <p>Returns <code>true</code> if s is <code>null</code>.</p> 629 * 630 * @param str the String to check 631 * @return if it is all zeros or <code>null</code> 632 */ 633 private static boolean isAllZeros(final String str) { 634 if (str == null) { 635 return true; 636 } 637 for (int i = str.length() - 1; i >= 0; i--) { 638 if (str.charAt(i) != '0') { 639 return false; 640 } 641 } 642 return str.length() > 0; 643 } 644 645 //----------------------------------------------------------------------- 646 /** 647 * <p>Convert a <code>String</code> to a <code>Float</code>.</p> 648 * 649 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 650 * 651 * @param str a <code>String</code> to convert, may be null 652 * @return converted <code>Float</code> (or null if the input is null) 653 * @throws NumberFormatException if the value cannot be converted 654 */ 655 public static Float createFloat(final String str) { 656 if (str == null) { 657 return null; 658 } 659 return Float.valueOf(str); 660 } 661 662 /** 663 * <p>Convert a <code>String</code> to a <code>Double</code>.</p> 664 * 665 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 666 * 667 * @param str a <code>String</code> to convert, may be null 668 * @return converted <code>Double</code> (or null if the input is null) 669 * @throws NumberFormatException if the value cannot be converted 670 */ 671 public static Double createDouble(final String str) { 672 if (str == null) { 673 return null; 674 } 675 return Double.valueOf(str); 676 } 677 678 /** 679 * <p>Convert a <code>String</code> to a <code>Integer</code>, handling 680 * hex (0xhhhh) and octal (0dddd) notations. 681 * N.B. a leading zero means octal; spaces are not trimmed.</p> 682 * 683 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 684 * 685 * @param str a <code>String</code> to convert, may be null 686 * @return converted <code>Integer</code> (or null if the input is null) 687 * @throws NumberFormatException if the value cannot be converted 688 */ 689 public static Integer createInteger(final String str) { 690 if (str == null) { 691 return null; 692 } 693 // decode() handles 0xAABD and 0777 (hex and octal) as well. 694 return Integer.decode(str); 695 } 696 697 /** 698 * <p>Convert a <code>String</code> to a <code>Long</code>; 699 * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. 700 * N.B. a leading zero means octal; spaces are not trimmed.</p> 701 * 702 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 703 * 704 * @param str a <code>String</code> to convert, may be null 705 * @return converted <code>Long</code> (or null if the input is null) 706 * @throws NumberFormatException if the value cannot be converted 707 */ 708 public static Long createLong(final String str) { 709 if (str == null) { 710 return null; 711 } 712 return Long.decode(str); 713 } 714 715 /** 716 * <p>Convert a <code>String</code> to a <code>BigInteger</code>; 717 * since 3.2 it handles hex (0x or #) and octal (0) notations.</p> 718 * 719 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 720 * 721 * @param str a <code>String</code> to convert, may be null 722 * @return converted <code>BigInteger</code> (or null if the input is null) 723 * @throws NumberFormatException if the value cannot be converted 724 */ 725 public static BigInteger createBigInteger(final String str) { 726 if (str == null) { 727 return null; 728 } 729 int pos = 0; // offset within string 730 int radix = 10; 731 boolean negate = false; // need to negate later? 732 if (str.startsWith("-")) { 733 negate = true; 734 pos = 1; 735 } 736 if (str.startsWith("0x", pos) || str.startsWith("0x", pos)) { // hex 737 radix = 16; 738 pos += 2; 739 } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) 740 radix = 16; 741 pos ++; 742 } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits 743 radix = 8; 744 pos ++; 745 } // default is to treat as decimal 746 747 final BigInteger value = new BigInteger(str.substring(pos), radix); 748 return negate ? value.negate() : value; 749 } 750 751 /** 752 * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p> 753 * 754 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 755 * 756 * @param str a <code>String</code> to convert, may be null 757 * @return converted <code>BigDecimal</code> (or null if the input is null) 758 * @throws NumberFormatException if the value cannot be converted 759 */ 760 public static BigDecimal createBigDecimal(final String str) { 761 if (str == null) { 762 return null; 763 } 764 // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException 765 if (StringUtils.isBlank(str)) { 766 throw new NumberFormatException("A blank string is not a valid number"); 767 } 768 if (str.trim().startsWith("--")) { 769 // this is protection for poorness in java.lang.BigDecimal. 770 // it accepts this as a legal value, but it does not appear 771 // to be in specification of class. OS X Java parses it to 772 // a wrong value. 773 throw new NumberFormatException(str + " is not a valid number."); 774 } 775 return new BigDecimal(str); 776 } 777 778 // Min in array 779 //-------------------------------------------------------------------- 780 /** 781 * <p>Returns the minimum value in an array.</p> 782 * 783 * @param array an array, must not be null or empty 784 * @return the minimum value in the array 785 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 786 * @throws IllegalArgumentException if <code>array</code> is empty 787 */ 788 public static long min(final long[] array) { 789 // Validates input 790 validateArray(array); 791 792 // Finds and returns min 793 long min = array[0]; 794 for (int i = 1; i < array.length; i++) { 795 if (array[i] < min) { 796 min = array[i]; 797 } 798 } 799 800 return min; 801 } 802 803 /** 804 * <p>Returns the minimum value in an array.</p> 805 * 806 * @param array an array, must not be null or empty 807 * @return the minimum value in the array 808 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 809 * @throws IllegalArgumentException if <code>array</code> is empty 810 */ 811 public static int min(final int[] array) { 812 // Validates input 813 validateArray(array); 814 815 // Finds and returns min 816 int min = array[0]; 817 for (int j = 1; j < array.length; j++) { 818 if (array[j] < min) { 819 min = array[j]; 820 } 821 } 822 823 return min; 824 } 825 826 /** 827 * <p>Returns the minimum value in an array.</p> 828 * 829 * @param array an array, must not be null or empty 830 * @return the minimum value in the array 831 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 832 * @throws IllegalArgumentException if <code>array</code> is empty 833 */ 834 public static short min(final short[] array) { 835 // Validates input 836 validateArray(array); 837 838 // Finds and returns min 839 short min = array[0]; 840 for (int i = 1; i < array.length; i++) { 841 if (array[i] < min) { 842 min = array[i]; 843 } 844 } 845 846 return min; 847 } 848 849 /** 850 * <p>Returns the minimum value in an array.</p> 851 * 852 * @param array an array, must not be null or empty 853 * @return the minimum value in the array 854 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 855 * @throws IllegalArgumentException if <code>array</code> is empty 856 */ 857 public static byte min(final byte[] array) { 858 // Validates input 859 validateArray(array); 860 861 // Finds and returns min 862 byte min = array[0]; 863 for (int i = 1; i < array.length; i++) { 864 if (array[i] < min) { 865 min = array[i]; 866 } 867 } 868 869 return min; 870 } 871 872 /** 873 * <p>Returns the minimum value in an array.</p> 874 * 875 * @param array an array, must not be null or empty 876 * @return the minimum value in the array 877 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 878 * @throws IllegalArgumentException if <code>array</code> is empty 879 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently 880 */ 881 public static double min(final double[] array) { 882 // Validates input 883 validateArray(array); 884 885 // Finds and returns min 886 double min = array[0]; 887 for (int i = 1; i < array.length; i++) { 888 if (Double.isNaN(array[i])) { 889 return Double.NaN; 890 } 891 if (array[i] < min) { 892 min = array[i]; 893 } 894 } 895 896 return min; 897 } 898 899 /** 900 * <p>Returns the minimum value in an array.</p> 901 * 902 * @param array an array, must not be null or empty 903 * @return the minimum value in the array 904 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 905 * @throws IllegalArgumentException if <code>array</code> is empty 906 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently 907 */ 908 public static float min(final float[] array) { 909 // Validates input 910 validateArray(array); 911 912 // Finds and returns min 913 float min = array[0]; 914 for (int i = 1; i < array.length; i++) { 915 if (Float.isNaN(array[i])) { 916 return Float.NaN; 917 } 918 if (array[i] < min) { 919 min = array[i]; 920 } 921 } 922 923 return min; 924 } 925 926 // Max in array 927 //-------------------------------------------------------------------- 928 /** 929 * <p>Returns the maximum value in an array.</p> 930 * 931 * @param array an array, must not be null or empty 932 * @return the minimum value in the array 933 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 934 * @throws IllegalArgumentException if <code>array</code> is empty 935 */ 936 public static long max(final long[] array) { 937 // Validates input 938 validateArray(array); 939 940 // Finds and returns max 941 long max = array[0]; 942 for (int j = 1; j < array.length; j++) { 943 if (array[j] > max) { 944 max = array[j]; 945 } 946 } 947 948 return max; 949 } 950 951 /** 952 * <p>Returns the maximum value in an array.</p> 953 * 954 * @param array an array, must not be null or empty 955 * @return the minimum value in the array 956 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 957 * @throws IllegalArgumentException if <code>array</code> is empty 958 */ 959 public static int max(final int[] array) { 960 // Validates input 961 validateArray(array); 962 963 // Finds and returns max 964 int max = array[0]; 965 for (int j = 1; j < array.length; j++) { 966 if (array[j] > max) { 967 max = array[j]; 968 } 969 } 970 971 return max; 972 } 973 974 /** 975 * <p>Returns the maximum value in an array.</p> 976 * 977 * @param array an array, must not be null or empty 978 * @return the minimum value in the array 979 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 980 * @throws IllegalArgumentException if <code>array</code> is empty 981 */ 982 public static short max(final short[] array) { 983 // Validates input 984 validateArray(array); 985 986 // Finds and returns max 987 short max = array[0]; 988 for (int i = 1; i < array.length; i++) { 989 if (array[i] > max) { 990 max = array[i]; 991 } 992 } 993 994 return max; 995 } 996 997 /** 998 * <p>Returns the maximum value in an array.</p> 999 * 1000 * @param array an array, must not be null or empty 1001 * @return the minimum value in the array 1002 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1003 * @throws IllegalArgumentException if <code>array</code> is empty 1004 */ 1005 public static byte max(final byte[] array) { 1006 // Validates input 1007 validateArray(array); 1008 1009 // Finds and returns max 1010 byte max = array[0]; 1011 for (int i = 1; i < array.length; i++) { 1012 if (array[i] > max) { 1013 max = array[i]; 1014 } 1015 } 1016 1017 return max; 1018 } 1019 1020 /** 1021 * <p>Returns the maximum value in an array.</p> 1022 * 1023 * @param array an array, must not be null or empty 1024 * @return the minimum value in the array 1025 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1026 * @throws IllegalArgumentException if <code>array</code> is empty 1027 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently 1028 */ 1029 public static double max(final double[] array) { 1030 // Validates input 1031 validateArray(array); 1032 1033 // Finds and returns max 1034 double max = array[0]; 1035 for (int j = 1; j < array.length; j++) { 1036 if (Double.isNaN(array[j])) { 1037 return Double.NaN; 1038 } 1039 if (array[j] > max) { 1040 max = array[j]; 1041 } 1042 } 1043 1044 return max; 1045 } 1046 1047 /** 1048 * <p>Returns the maximum value in an array.</p> 1049 * 1050 * @param array an array, must not be null or empty 1051 * @return the minimum value in the array 1052 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1053 * @throws IllegalArgumentException if <code>array</code> is empty 1054 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently 1055 */ 1056 public static float max(final float[] array) { 1057 // Validates input 1058 validateArray(array); 1059 1060 // Finds and returns max 1061 float max = array[0]; 1062 for (int j = 1; j < array.length; j++) { 1063 if (Float.isNaN(array[j])) { 1064 return Float.NaN; 1065 } 1066 if (array[j] > max) { 1067 max = array[j]; 1068 } 1069 } 1070 1071 return max; 1072 } 1073 1074 /** 1075 * Checks if the specified array is neither null nor empty. 1076 * 1077 * @param array the array to check 1078 * @throws IllegalArgumentException if {@code array} is either {@code null} or empty 1079 */ 1080 private static void validateArray(final Object array) { 1081 if (array == null) { 1082 throw new IllegalArgumentException("The Array must not be null"); 1083 } else if (Array.getLength(array) == 0) { 1084 throw new IllegalArgumentException("Array cannot be empty."); 1085 } 1086 } 1087 1088 // 3 param min 1089 //----------------------------------------------------------------------- 1090 /** 1091 * <p>Gets the minimum of three <code>long</code> values.</p> 1092 * 1093 * @param a value 1 1094 * @param b value 2 1095 * @param c value 3 1096 * @return the smallest of the values 1097 */ 1098 public static long min(long a, final long b, final long c) { 1099 if (b < a) { 1100 a = b; 1101 } 1102 if (c < a) { 1103 a = c; 1104 } 1105 return a; 1106 } 1107 1108 /** 1109 * <p>Gets the minimum of three <code>int</code> values.</p> 1110 * 1111 * @param a value 1 1112 * @param b value 2 1113 * @param c value 3 1114 * @return the smallest of the values 1115 */ 1116 public static int min(int a, final int b, final int c) { 1117 if (b < a) { 1118 a = b; 1119 } 1120 if (c < a) { 1121 a = c; 1122 } 1123 return a; 1124 } 1125 1126 /** 1127 * <p>Gets the minimum of three <code>short</code> values.</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 */ 1134 public static short min(short a, final short b, final short c) { 1135 if (b < a) { 1136 a = b; 1137 } 1138 if (c < a) { 1139 a = c; 1140 } 1141 return a; 1142 } 1143 1144 /** 1145 * <p>Gets the minimum of three <code>byte</code> values.</p> 1146 * 1147 * @param a value 1 1148 * @param b value 2 1149 * @param c value 3 1150 * @return the smallest of the values 1151 */ 1152 public static byte min(byte a, final byte b, final byte c) { 1153 if (b < a) { 1154 a = b; 1155 } 1156 if (c < a) { 1157 a = c; 1158 } 1159 return a; 1160 } 1161 1162 /** 1163 * <p>Gets the minimum of three <code>double</code> values.</p> 1164 * 1165 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1166 * returned. Infinity is handled.</p> 1167 * 1168 * @param a value 1 1169 * @param b value 2 1170 * @param c value 3 1171 * @return the smallest of the values 1172 * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently 1173 */ 1174 public static double min(final double a, final double b, final double c) { 1175 return Math.min(Math.min(a, b), c); 1176 } 1177 1178 /** 1179 * <p>Gets the minimum of three <code>float</code> values.</p> 1180 * 1181 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1182 * returned. Infinity is handled.</p> 1183 * 1184 * @param a value 1 1185 * @param b value 2 1186 * @param c value 3 1187 * @return the smallest of the values 1188 * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently 1189 */ 1190 public static float min(final float a, final float b, final float c) { 1191 return Math.min(Math.min(a, b), c); 1192 } 1193 1194 // 3 param max 1195 //----------------------------------------------------------------------- 1196 /** 1197 * <p>Gets the maximum of three <code>long</code> values.</p> 1198 * 1199 * @param a value 1 1200 * @param b value 2 1201 * @param c value 3 1202 * @return the largest of the values 1203 */ 1204 public static long max(long a, final long b, final long c) { 1205 if (b > a) { 1206 a = b; 1207 } 1208 if (c > a) { 1209 a = c; 1210 } 1211 return a; 1212 } 1213 1214 /** 1215 * <p>Gets the maximum of three <code>int</code> values.</p> 1216 * 1217 * @param a value 1 1218 * @param b value 2 1219 * @param c value 3 1220 * @return the largest of the values 1221 */ 1222 public static int max(int a, final int b, final int c) { 1223 if (b > a) { 1224 a = b; 1225 } 1226 if (c > a) { 1227 a = c; 1228 } 1229 return a; 1230 } 1231 1232 /** 1233 * <p>Gets the maximum of three <code>short</code> values.</p> 1234 * 1235 * @param a value 1 1236 * @param b value 2 1237 * @param c value 3 1238 * @return the largest of the values 1239 */ 1240 public static short max(short a, final short b, final short c) { 1241 if (b > a) { 1242 a = b; 1243 } 1244 if (c > a) { 1245 a = c; 1246 } 1247 return a; 1248 } 1249 1250 /** 1251 * <p>Gets the maximum of three <code>byte</code> values.</p> 1252 * 1253 * @param a value 1 1254 * @param b value 2 1255 * @param c value 3 1256 * @return the largest of the values 1257 */ 1258 public static byte max(byte a, final byte b, final byte c) { 1259 if (b > a) { 1260 a = b; 1261 } 1262 if (c > a) { 1263 a = c; 1264 } 1265 return a; 1266 } 1267 1268 /** 1269 * <p>Gets the maximum of three <code>double</code> values.</p> 1270 * 1271 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1272 * returned. Infinity is handled.</p> 1273 * 1274 * @param a value 1 1275 * @param b value 2 1276 * @param c value 3 1277 * @return the largest of the values 1278 * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently 1279 */ 1280 public static double max(final double a, final double b, final double c) { 1281 return Math.max(Math.max(a, b), c); 1282 } 1283 1284 /** 1285 * <p>Gets the maximum of three <code>float</code> values.</p> 1286 * 1287 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1288 * returned. Infinity is handled.</p> 1289 * 1290 * @param a value 1 1291 * @param b value 2 1292 * @param c value 3 1293 * @return the largest of the values 1294 * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently 1295 */ 1296 public static float max(final float a, final float b, final float c) { 1297 return Math.max(Math.max(a, b), c); 1298 } 1299 1300 //----------------------------------------------------------------------- 1301 /** 1302 * <p>Checks whether the <code>String</code> contains only 1303 * digit characters.</p> 1304 * 1305 * <p><code>Null</code> and empty String will return 1306 * <code>false</code>.</p> 1307 * 1308 * @param str the <code>String</code> to check 1309 * @return <code>true</code> if str contains only Unicode numeric 1310 */ 1311 public static boolean isDigits(final String str) { 1312 if (StringUtils.isEmpty(str)) { 1313 return false; 1314 } 1315 for (int i = 0; i < str.length(); i++) { 1316 if (!Character.isDigit(str.charAt(i))) { 1317 return false; 1318 } 1319 } 1320 return true; 1321 } 1322 1323 /** 1324 * <p>Checks whether the String a valid Java number.</p> 1325 * 1326 * <p>Valid numbers include hexadecimal marked with the <code>0x</code> 1327 * qualifier, scientific notation and numbers marked with a type 1328 * qualifier (e.g. 123L).</p> 1329 * 1330 * <p><code>Null</code> and empty String will return 1331 * <code>false</code>.</p> 1332 * 1333 * @param str the <code>String</code> to check 1334 * @return <code>true</code> if the string is a correctly formatted number 1335 * @since 3.3 the code supports hex {@code 0Xhhh} and octal {@code 0ddd} validation 1336 */ 1337 public static boolean isNumber(final String str) { 1338 if (StringUtils.isEmpty(str)) { 1339 return false; 1340 } 1341 final char[] chars = str.toCharArray(); 1342 int sz = chars.length; 1343 boolean hasExp = false; 1344 boolean hasDecPoint = false; 1345 boolean allowSigns = false; 1346 boolean foundDigit = false; 1347 // deal with any possible sign up front 1348 final int start = (chars[0] == '-') ? 1 : 0; 1349 if (sz > start + 1 && chars[start] == '0') { // leading 0 1350 if ( 1351 (chars[start + 1] == 'x') || 1352 (chars[start + 1] == 'X') 1353 ) { // leading 0x/0X 1354 int i = start + 2; 1355 if (i == sz) { 1356 return false; // str == "0x" 1357 } 1358 // checking hex (it can't be anything else) 1359 for (; i < chars.length; i++) { 1360 if ((chars[i] < '0' || chars[i] > '9') 1361 && (chars[i] < 'a' || chars[i] > 'f') 1362 && (chars[i] < 'A' || chars[i] > 'F')) { 1363 return false; 1364 } 1365 } 1366 return true; 1367 } else if (Character.isDigit(chars[start + 1])) { 1368 // leading 0, but not hex, must be octal 1369 int i = start + 1; 1370 for (; i < chars.length; i++) { 1371 if (chars[i] < '0' || chars[i] > '7') { 1372 return false; 1373 } 1374 } 1375 return true; 1376 } 1377 } 1378 sz--; // don't want to loop to the last char, check it afterwords 1379 // for type qualifiers 1380 int i = start; 1381 // loop to the next to last char or to the last char if we need another digit to 1382 // make a valid number (e.g. chars[0..5] = "1234E") 1383 while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { 1384 if (chars[i] >= '0' && chars[i] <= '9') { 1385 foundDigit = true; 1386 allowSigns = false; 1387 1388 } else if (chars[i] == '.') { 1389 if (hasDecPoint || hasExp) { 1390 // two decimal points or dec in exponent 1391 return false; 1392 } 1393 hasDecPoint = true; 1394 } else if (chars[i] == 'e' || chars[i] == 'E') { 1395 // we've already taken care of hex. 1396 if (hasExp) { 1397 // two E's 1398 return false; 1399 } 1400 if (!foundDigit) { 1401 return false; 1402 } 1403 hasExp = true; 1404 allowSigns = true; 1405 } else if (chars[i] == '+' || chars[i] == '-') { 1406 if (!allowSigns) { 1407 return false; 1408 } 1409 allowSigns = false; 1410 foundDigit = false; // we need a digit after the E 1411 } else { 1412 return false; 1413 } 1414 i++; 1415 } 1416 if (i < chars.length) { 1417 if (chars[i] >= '0' && chars[i] <= '9') { 1418 // no type qualifier, OK 1419 return true; 1420 } 1421 if (chars[i] == 'e' || chars[i] == 'E') { 1422 // can't have an E at the last byte 1423 return false; 1424 } 1425 if (chars[i] == '.') { 1426 if (hasDecPoint || hasExp) { 1427 // two decimal points or dec in exponent 1428 return false; 1429 } 1430 // single trailing decimal point after non-exponent is ok 1431 return foundDigit; 1432 } 1433 if (!allowSigns 1434 && (chars[i] == 'd' 1435 || chars[i] == 'D' 1436 || chars[i] == 'f' 1437 || chars[i] == 'F')) { 1438 return foundDigit; 1439 } 1440 if (chars[i] == 'l' 1441 || chars[i] == 'L') { 1442 // not allowing L with an exponent or decimal point 1443 return foundDigit && !hasExp && !hasDecPoint; 1444 } 1445 // last character is illegal 1446 return false; 1447 } 1448 // allowSigns is true iff the val ends in 'E' 1449 // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass 1450 return !allowSigns && foundDigit; 1451 } 1452 1453}