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 1507169 2013-07-26 01:03:52Z sebb $ 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 and octal notations.</p> 681 * 682 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 683 * 684 * @param str a <code>String</code> to convert, may be null 685 * @return converted <code>Integer</code> (or null if the input is null) 686 * @throws NumberFormatException if the value cannot be converted 687 */ 688 public static Integer createInteger(final String str) { 689 if (str == null) { 690 return null; 691 } 692 // decode() handles 0xAABD and 0777 (hex and octal) as well. 693 return Integer.decode(str); 694 } 695 696 /** 697 * <p>Convert a <code>String</code> to a <code>Long</code>; 698 * since 3.1 it handles hex and octal notations.</p> 699 * 700 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 701 * 702 * @param str a <code>String</code> to convert, may be null 703 * @return converted <code>Long</code> (or null if the input is null) 704 * @throws NumberFormatException if the value cannot be converted 705 */ 706 public static Long createLong(final String str) { 707 if (str == null) { 708 return null; 709 } 710 return Long.decode(str); 711 } 712 713 /** 714 * <p>Convert a <code>String</code> to a <code>BigInteger</code>; 715 * since 3.2 it handles hex (0x or #) and octal (0) notations.</p> 716 * 717 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 718 * 719 * @param str a <code>String</code> to convert, may be null 720 * @return converted <code>BigInteger</code> (or null if the input is null) 721 * @throws NumberFormatException if the value cannot be converted 722 */ 723 public static BigInteger createBigInteger(final String str) { 724 if (str == null) { 725 return null; 726 } 727 int pos = 0; // offset within string 728 int radix = 10; 729 boolean negate = false; // need to negate later? 730 if (str.startsWith("-")) { 731 negate = true; 732 pos = 1; 733 } 734 if (str.startsWith("0x", pos) || str.startsWith("0x", pos)) { // hex 735 radix = 16; 736 pos += 2; 737 } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) 738 radix = 16; 739 pos ++; 740 } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits 741 radix = 8; 742 pos ++; 743 } // default is to treat as decimal 744 745 final BigInteger value = new BigInteger(str.substring(pos), radix); 746 return negate ? value.negate() : value; 747 } 748 749 /** 750 * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p> 751 * 752 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 753 * 754 * @param str a <code>String</code> to convert, may be null 755 * @return converted <code>BigDecimal</code> (or null if the input is null) 756 * @throws NumberFormatException if the value cannot be converted 757 */ 758 public static BigDecimal createBigDecimal(final String str) { 759 if (str == null) { 760 return null; 761 } 762 // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException 763 if (StringUtils.isBlank(str)) { 764 throw new NumberFormatException("A blank string is not a valid number"); 765 } 766 if (str.trim().startsWith("--")) { 767 // this is protection for poorness in java.lang.BigDecimal. 768 // it accepts this as a legal value, but it does not appear 769 // to be in specification of class. OS X Java parses it to 770 // a wrong value. 771 throw new NumberFormatException(str + " is not a valid number."); 772 } 773 return new BigDecimal(str); 774 } 775 776 // Min in array 777 //-------------------------------------------------------------------- 778 /** 779 * <p>Returns the minimum value in an array.</p> 780 * 781 * @param array an array, must not be null or empty 782 * @return the minimum value in the array 783 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 784 * @throws IllegalArgumentException if <code>array</code> is empty 785 */ 786 public static long min(final long[] array) { 787 // Validates input 788 validateArray(array); 789 790 // Finds and returns min 791 long min = array[0]; 792 for (int i = 1; i < array.length; i++) { 793 if (array[i] < min) { 794 min = array[i]; 795 } 796 } 797 798 return min; 799 } 800 801 /** 802 * <p>Returns the minimum value in an array.</p> 803 * 804 * @param array an array, must not be null or empty 805 * @return the minimum value in the array 806 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 807 * @throws IllegalArgumentException if <code>array</code> is empty 808 */ 809 public static int min(final int[] array) { 810 // Validates input 811 validateArray(array); 812 813 // Finds and returns min 814 int min = array[0]; 815 for (int j = 1; j < array.length; j++) { 816 if (array[j] < min) { 817 min = array[j]; 818 } 819 } 820 821 return min; 822 } 823 824 /** 825 * <p>Returns the minimum value in an array.</p> 826 * 827 * @param array an array, must not be null or empty 828 * @return the minimum value in the array 829 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 830 * @throws IllegalArgumentException if <code>array</code> is empty 831 */ 832 public static short min(final short[] array) { 833 // Validates input 834 validateArray(array); 835 836 // Finds and returns min 837 short min = array[0]; 838 for (int i = 1; i < array.length; i++) { 839 if (array[i] < min) { 840 min = array[i]; 841 } 842 } 843 844 return min; 845 } 846 847 /** 848 * <p>Returns the minimum value in an array.</p> 849 * 850 * @param array an array, must not be null or empty 851 * @return the minimum value in the array 852 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 853 * @throws IllegalArgumentException if <code>array</code> is empty 854 */ 855 public static byte min(final byte[] array) { 856 // Validates input 857 validateArray(array); 858 859 // Finds and returns min 860 byte min = array[0]; 861 for (int i = 1; i < array.length; i++) { 862 if (array[i] < min) { 863 min = array[i]; 864 } 865 } 866 867 return min; 868 } 869 870 /** 871 * <p>Returns the minimum value in an array.</p> 872 * 873 * @param array an array, must not be null or empty 874 * @return the minimum value in the array 875 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 876 * @throws IllegalArgumentException if <code>array</code> is empty 877 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently 878 */ 879 public static double min(final double[] array) { 880 // Validates input 881 validateArray(array); 882 883 // Finds and returns min 884 double min = array[0]; 885 for (int i = 1; i < array.length; i++) { 886 if (Double.isNaN(array[i])) { 887 return Double.NaN; 888 } 889 if (array[i] < min) { 890 min = array[i]; 891 } 892 } 893 894 return min; 895 } 896 897 /** 898 * <p>Returns the minimum value in an array.</p> 899 * 900 * @param array an array, must not be null or empty 901 * @return the minimum value in the array 902 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 903 * @throws IllegalArgumentException if <code>array</code> is empty 904 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently 905 */ 906 public static float min(final float[] array) { 907 // Validates input 908 validateArray(array); 909 910 // Finds and returns min 911 float min = array[0]; 912 for (int i = 1; i < array.length; i++) { 913 if (Float.isNaN(array[i])) { 914 return Float.NaN; 915 } 916 if (array[i] < min) { 917 min = array[i]; 918 } 919 } 920 921 return min; 922 } 923 924 // Max in array 925 //-------------------------------------------------------------------- 926 /** 927 * <p>Returns the maximum value in an array.</p> 928 * 929 * @param array an array, must not be null or empty 930 * @return the minimum value in the array 931 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 932 * @throws IllegalArgumentException if <code>array</code> is empty 933 */ 934 public static long max(final long[] array) { 935 // Validates input 936 validateArray(array); 937 938 // Finds and returns max 939 long max = array[0]; 940 for (int j = 1; j < array.length; j++) { 941 if (array[j] > max) { 942 max = array[j]; 943 } 944 } 945 946 return max; 947 } 948 949 /** 950 * <p>Returns the maximum value in an array.</p> 951 * 952 * @param array an array, must not be null or empty 953 * @return the minimum value in the array 954 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 955 * @throws IllegalArgumentException if <code>array</code> is empty 956 */ 957 public static int max(final int[] array) { 958 // Validates input 959 validateArray(array); 960 961 // Finds and returns max 962 int max = array[0]; 963 for (int j = 1; j < array.length; j++) { 964 if (array[j] > max) { 965 max = array[j]; 966 } 967 } 968 969 return max; 970 } 971 972 /** 973 * <p>Returns the maximum value in an array.</p> 974 * 975 * @param array an array, must not be null or empty 976 * @return the minimum value in the array 977 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 978 * @throws IllegalArgumentException if <code>array</code> is empty 979 */ 980 public static short max(final short[] array) { 981 // Validates input 982 validateArray(array); 983 984 // Finds and returns max 985 short max = array[0]; 986 for (int i = 1; i < array.length; i++) { 987 if (array[i] > max) { 988 max = array[i]; 989 } 990 } 991 992 return max; 993 } 994 995 /** 996 * <p>Returns the maximum value in an array.</p> 997 * 998 * @param array an array, must not be null or empty 999 * @return the minimum value in the array 1000 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1001 * @throws IllegalArgumentException if <code>array</code> is empty 1002 */ 1003 public static byte max(final byte[] array) { 1004 // Validates input 1005 validateArray(array); 1006 1007 // Finds and returns max 1008 byte max = array[0]; 1009 for (int i = 1; i < array.length; i++) { 1010 if (array[i] > max) { 1011 max = array[i]; 1012 } 1013 } 1014 1015 return max; 1016 } 1017 1018 /** 1019 * <p>Returns the maximum value in an array.</p> 1020 * 1021 * @param array an array, must not be null or empty 1022 * @return the minimum value in the array 1023 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1024 * @throws IllegalArgumentException if <code>array</code> is empty 1025 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently 1026 */ 1027 public static double max(final double[] array) { 1028 // Validates input 1029 validateArray(array); 1030 1031 // Finds and returns max 1032 double max = array[0]; 1033 for (int j = 1; j < array.length; j++) { 1034 if (Double.isNaN(array[j])) { 1035 return Double.NaN; 1036 } 1037 if (array[j] > max) { 1038 max = array[j]; 1039 } 1040 } 1041 1042 return max; 1043 } 1044 1045 /** 1046 * <p>Returns the maximum value in an array.</p> 1047 * 1048 * @param array an array, must not be null or empty 1049 * @return the minimum value in the array 1050 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1051 * @throws IllegalArgumentException if <code>array</code> is empty 1052 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently 1053 */ 1054 public static float max(final float[] array) { 1055 // Validates input 1056 validateArray(array); 1057 1058 // Finds and returns max 1059 float max = array[0]; 1060 for (int j = 1; j < array.length; j++) { 1061 if (Float.isNaN(array[j])) { 1062 return Float.NaN; 1063 } 1064 if (array[j] > max) { 1065 max = array[j]; 1066 } 1067 } 1068 1069 return max; 1070 } 1071 1072 /** 1073 * Checks if the specified array is neither null nor empty. 1074 * 1075 * @param array the array to check 1076 * @throws IllegalArgumentException if {@code array} is either {@code null} or empty 1077 */ 1078 private static void validateArray(final Object array) { 1079 if (array == null) { 1080 throw new IllegalArgumentException("The Array must not be null"); 1081 } else if (Array.getLength(array) == 0) { 1082 throw new IllegalArgumentException("Array cannot be empty."); 1083 } 1084 } 1085 1086 // 3 param min 1087 //----------------------------------------------------------------------- 1088 /** 1089 * <p>Gets the minimum of three <code>long</code> values.</p> 1090 * 1091 * @param a value 1 1092 * @param b value 2 1093 * @param c value 3 1094 * @return the smallest of the values 1095 */ 1096 public static long min(long a, final long b, final long c) { 1097 if (b < a) { 1098 a = b; 1099 } 1100 if (c < a) { 1101 a = c; 1102 } 1103 return a; 1104 } 1105 1106 /** 1107 * <p>Gets the minimum of three <code>int</code> values.</p> 1108 * 1109 * @param a value 1 1110 * @param b value 2 1111 * @param c value 3 1112 * @return the smallest of the values 1113 */ 1114 public static int min(int a, final int b, final int c) { 1115 if (b < a) { 1116 a = b; 1117 } 1118 if (c < a) { 1119 a = c; 1120 } 1121 return a; 1122 } 1123 1124 /** 1125 * <p>Gets the minimum of three <code>short</code> values.</p> 1126 * 1127 * @param a value 1 1128 * @param b value 2 1129 * @param c value 3 1130 * @return the smallest of the values 1131 */ 1132 public static short min(short a, final short b, final short c) { 1133 if (b < a) { 1134 a = b; 1135 } 1136 if (c < a) { 1137 a = c; 1138 } 1139 return a; 1140 } 1141 1142 /** 1143 * <p>Gets the minimum of three <code>byte</code> values.</p> 1144 * 1145 * @param a value 1 1146 * @param b value 2 1147 * @param c value 3 1148 * @return the smallest of the values 1149 */ 1150 public static byte min(byte a, final byte b, final byte c) { 1151 if (b < a) { 1152 a = b; 1153 } 1154 if (c < a) { 1155 a = c; 1156 } 1157 return a; 1158 } 1159 1160 /** 1161 * <p>Gets the minimum of three <code>double</code> values.</p> 1162 * 1163 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1164 * returned. Infinity is handled.</p> 1165 * 1166 * @param a value 1 1167 * @param b value 2 1168 * @param c value 3 1169 * @return the smallest of the values 1170 * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently 1171 */ 1172 public static double min(final double a, final double b, final double c) { 1173 return Math.min(Math.min(a, b), c); 1174 } 1175 1176 /** 1177 * <p>Gets the minimum of three <code>float</code> values.</p> 1178 * 1179 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1180 * returned. Infinity is handled.</p> 1181 * 1182 * @param a value 1 1183 * @param b value 2 1184 * @param c value 3 1185 * @return the smallest of the values 1186 * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently 1187 */ 1188 public static float min(final float a, final float b, final float c) { 1189 return Math.min(Math.min(a, b), c); 1190 } 1191 1192 // 3 param max 1193 //----------------------------------------------------------------------- 1194 /** 1195 * <p>Gets the maximum of three <code>long</code> values.</p> 1196 * 1197 * @param a value 1 1198 * @param b value 2 1199 * @param c value 3 1200 * @return the largest of the values 1201 */ 1202 public static long max(long a, final long b, final long c) { 1203 if (b > a) { 1204 a = b; 1205 } 1206 if (c > a) { 1207 a = c; 1208 } 1209 return a; 1210 } 1211 1212 /** 1213 * <p>Gets the maximum of three <code>int</code> values.</p> 1214 * 1215 * @param a value 1 1216 * @param b value 2 1217 * @param c value 3 1218 * @return the largest of the values 1219 */ 1220 public static int max(int a, final int b, final int c) { 1221 if (b > a) { 1222 a = b; 1223 } 1224 if (c > a) { 1225 a = c; 1226 } 1227 return a; 1228 } 1229 1230 /** 1231 * <p>Gets the maximum of three <code>short</code> values.</p> 1232 * 1233 * @param a value 1 1234 * @param b value 2 1235 * @param c value 3 1236 * @return the largest of the values 1237 */ 1238 public static short max(short a, final short b, final short c) { 1239 if (b > a) { 1240 a = b; 1241 } 1242 if (c > a) { 1243 a = c; 1244 } 1245 return a; 1246 } 1247 1248 /** 1249 * <p>Gets the maximum of three <code>byte</code> values.</p> 1250 * 1251 * @param a value 1 1252 * @param b value 2 1253 * @param c value 3 1254 * @return the largest of the values 1255 */ 1256 public static byte max(byte a, final byte b, final byte c) { 1257 if (b > a) { 1258 a = b; 1259 } 1260 if (c > a) { 1261 a = c; 1262 } 1263 return a; 1264 } 1265 1266 /** 1267 * <p>Gets the maximum of three <code>double</code> values.</p> 1268 * 1269 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1270 * returned. Infinity is handled.</p> 1271 * 1272 * @param a value 1 1273 * @param b value 2 1274 * @param c value 3 1275 * @return the largest of the values 1276 * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently 1277 */ 1278 public static double max(final double a, final double b, final double c) { 1279 return Math.max(Math.max(a, b), c); 1280 } 1281 1282 /** 1283 * <p>Gets the maximum of three <code>float</code> values.</p> 1284 * 1285 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1286 * returned. Infinity is handled.</p> 1287 * 1288 * @param a value 1 1289 * @param b value 2 1290 * @param c value 3 1291 * @return the largest of the values 1292 * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently 1293 */ 1294 public static float max(final float a, final float b, final float c) { 1295 return Math.max(Math.max(a, b), c); 1296 } 1297 1298 //----------------------------------------------------------------------- 1299 /** 1300 * <p>Checks whether the <code>String</code> contains only 1301 * digit characters.</p> 1302 * 1303 * <p><code>Null</code> and empty String will return 1304 * <code>false</code>.</p> 1305 * 1306 * @param str the <code>String</code> to check 1307 * @return <code>true</code> if str contains only Unicode numeric 1308 */ 1309 public static boolean isDigits(final String str) { 1310 if (StringUtils.isEmpty(str)) { 1311 return false; 1312 } 1313 for (int i = 0; i < str.length(); i++) { 1314 if (!Character.isDigit(str.charAt(i))) { 1315 return false; 1316 } 1317 } 1318 return true; 1319 } 1320 1321 /** 1322 * <p>Checks whether the String a valid Java number.</p> 1323 * 1324 * <p>Valid numbers include hexadecimal marked with the <code>0x</code> 1325 * qualifier, scientific notation and numbers marked with a type 1326 * qualifier (e.g. 123L).</p> 1327 * 1328 * <p><code>Null</code> and empty String will return 1329 * <code>false</code>.</p> 1330 * 1331 * @param str the <code>String</code> to check 1332 * @return <code>true</code> if the string is a correctly formatted number 1333 */ 1334 public static boolean isNumber(final String str) { 1335 if (StringUtils.isEmpty(str)) { 1336 return false; 1337 } 1338 final char[] chars = str.toCharArray(); 1339 int sz = chars.length; 1340 boolean hasExp = false; 1341 boolean hasDecPoint = false; 1342 boolean allowSigns = false; 1343 boolean foundDigit = false; 1344 // deal with any possible sign up front 1345 final int start = (chars[0] == '-') ? 1 : 0; 1346 if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') { 1347 int i = start + 2; 1348 if (i == sz) { 1349 return false; // str == "0x" 1350 } 1351 // checking hex (it can't be anything else) 1352 for (; i < chars.length; i++) { 1353 if ((chars[i] < '0' || chars[i] > '9') 1354 && (chars[i] < 'a' || chars[i] > 'f') 1355 && (chars[i] < 'A' || chars[i] > 'F')) { 1356 return false; 1357 } 1358 } 1359 return true; 1360 } 1361 sz--; // don't want to loop to the last char, check it afterwords 1362 // for type qualifiers 1363 int i = start; 1364 // loop to the next to last char or to the last char if we need another digit to 1365 // make a valid number (e.g. chars[0..5] = "1234E") 1366 while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { 1367 if (chars[i] >= '0' && chars[i] <= '9') { 1368 foundDigit = true; 1369 allowSigns = false; 1370 1371 } else if (chars[i] == '.') { 1372 if (hasDecPoint || hasExp) { 1373 // two decimal points or dec in exponent 1374 return false; 1375 } 1376 hasDecPoint = true; 1377 } else if (chars[i] == 'e' || chars[i] == 'E') { 1378 // we've already taken care of hex. 1379 if (hasExp) { 1380 // two E's 1381 return false; 1382 } 1383 if (!foundDigit) { 1384 return false; 1385 } 1386 hasExp = true; 1387 allowSigns = true; 1388 } else if (chars[i] == '+' || chars[i] == '-') { 1389 if (!allowSigns) { 1390 return false; 1391 } 1392 allowSigns = false; 1393 foundDigit = false; // we need a digit after the E 1394 } else { 1395 return false; 1396 } 1397 i++; 1398 } 1399 if (i < chars.length) { 1400 if (chars[i] >= '0' && chars[i] <= '9') { 1401 // no type qualifier, OK 1402 return true; 1403 } 1404 if (chars[i] == 'e' || chars[i] == 'E') { 1405 // can't have an E at the last byte 1406 return false; 1407 } 1408 if (chars[i] == '.') { 1409 if (hasDecPoint || hasExp) { 1410 // two decimal points or dec in exponent 1411 return false; 1412 } 1413 // single trailing decimal point after non-exponent is ok 1414 return foundDigit; 1415 } 1416 if (!allowSigns 1417 && (chars[i] == 'd' 1418 || chars[i] == 'D' 1419 || chars[i] == 'f' 1420 || chars[i] == 'F')) { 1421 return foundDigit; 1422 } 1423 if (chars[i] == 'l' 1424 || chars[i] == 'L') { 1425 // not allowing L with an exponent or decimal point 1426 return foundDigit && !hasExp && !hasDecPoint; 1427 } 1428 // last character is illegal 1429 return false; 1430 } 1431 // allowSigns is true iff the val ends in 'E' 1432 // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass 1433 return !allowSigns && foundDigit; 1434 } 1435 1436}