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