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