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 1448286 2013-02-20 16:47:18Z tn $ 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</code> or <code>-0x</code> (lower or upper case), it 423 * will be interpreted as a hexadecimal integer - or long, if the number of digits after the 0x 424 * prefix is more than 8. 425 * Values with leading <code>0</code>'s will not be interpreted as octal.</p> 426 * 427 * <p>Then, the value is examined for a type qualifier on the end, i.e. one of 428 * <code>'f','F','d','D','l','L'</code>. If it is found, it starts 429 * trying to create successively larger types from the type specified 430 * until one is found that can represent the value.</p> 431 * 432 * <p>If a type specifier is not found, it will check for a decimal point 433 * and then try successively larger types from <code>Integer</code> to 434 * <code>BigInteger</code> and from <code>Float</code> to 435 * <code>BigDecimal</code>.</p> 436 * 437 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 438 * 439 * <p>This method does not trim the input string, i.e., strings with leading 440 * or trailing spaces will generate NumberFormatExceptions.</p> 441 * 442 * @param str String containing a number, may be null 443 * @return Number created from the string (or null if the input is null) 444 * @throws NumberFormatException if the value cannot be converted 445 */ 446 public static Number createNumber(final String str) throws NumberFormatException { 447 if (str == null) { 448 return null; 449 } 450 if (StringUtils.isBlank(str)) { 451 throw new NumberFormatException("A blank string is not a valid number"); 452 } 453 // Need to deal with all possible hex prefixes here 454 final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; 455 int pfxLen = 0; 456 for(final String pfx : hex_prefixes) { 457 if (str.startsWith(pfx)) { 458 pfxLen += pfx.length(); 459 break; 460 } 461 } 462 if (pfxLen > 0) { 463 final int hexDigits = str.length() - pfxLen; 464 if (hexDigits > 16) { // too many for Long 465 return createBigInteger(str); 466 } 467 if (hexDigits > 8) { // too many for an int 468 return createLong(str); 469 } 470 return createInteger(str); 471 } 472 final char lastChar = str.charAt(str.length() - 1); 473 String mant; 474 String dec; 475 String exp; 476 final int decPos = str.indexOf('.'); 477 final int expPos = str.indexOf('e') + str.indexOf('E') + 1; 478 479 if (decPos > -1) { 480 481 if (expPos > -1) { 482 if (expPos < decPos || expPos > str.length()) { 483 throw new NumberFormatException(str + " is not a valid number."); 484 } 485 dec = str.substring(decPos + 1, expPos); 486 } else { 487 dec = str.substring(decPos + 1); 488 } 489 mant = str.substring(0, decPos); 490 } else { 491 if (expPos > -1) { 492 if (expPos > str.length()) { 493 throw new NumberFormatException(str + " is not a valid number."); 494 } 495 mant = str.substring(0, expPos); 496 } else { 497 mant = str; 498 } 499 dec = null; 500 } 501 if (!Character.isDigit(lastChar) && lastChar != '.') { 502 if (expPos > -1 && expPos < str.length() - 1) { 503 exp = str.substring(expPos + 1, str.length() - 1); 504 } else { 505 exp = null; 506 } 507 //Requesting a specific type.. 508 final String numeric = str.substring(0, str.length() - 1); 509 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); 510 switch (lastChar) { 511 case 'l' : 512 case 'L' : 513 if (dec == null 514 && exp == null 515 && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { 516 try { 517 return createLong(numeric); 518 } catch (final NumberFormatException nfe) { // NOPMD 519 // Too big for a long 520 } 521 return createBigInteger(numeric); 522 523 } 524 throw new NumberFormatException(str + " is not a valid number."); 525 case 'f' : 526 case 'F' : 527 try { 528 final Float f = NumberUtils.createFloat(numeric); 529 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { 530 //If it's too big for a float or the float value = 0 and the string 531 //has non-zeros in it, then float does not have the precision we want 532 return f; 533 } 534 535 } catch (final NumberFormatException nfe) { // NOPMD 536 // ignore the bad number 537 } 538 //$FALL-THROUGH$ 539 case 'd' : 540 case 'D' : 541 try { 542 final Double d = NumberUtils.createDouble(numeric); 543 if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { 544 return d; 545 } 546 } catch (final NumberFormatException nfe) { // NOPMD 547 // ignore the bad number 548 } 549 try { 550 return createBigDecimal(numeric); 551 } catch (final NumberFormatException e) { // NOPMD 552 // ignore the bad number 553 } 554 //$FALL-THROUGH$ 555 default : 556 throw new NumberFormatException(str + " is not a valid number."); 557 558 } 559 } else { 560 //User doesn't have a preference on the return type, so let's start 561 //small and go from there... 562 if (expPos > -1 && expPos < str.length() - 1) { 563 exp = str.substring(expPos + 1, str.length()); 564 } else { 565 exp = null; 566 } 567 if (dec == null && exp == null) { 568 //Must be an int,long,bigint 569 try { 570 return createInteger(str); 571 } catch (final NumberFormatException nfe) { // NOPMD 572 // ignore the bad number 573 } 574 try { 575 return createLong(str); 576 } catch (final NumberFormatException nfe) { // NOPMD 577 // ignore the bad number 578 } 579 return createBigInteger(str); 580 581 } else { 582 //Must be a float,double,BigDec 583 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); 584 try { 585 final Float f = createFloat(str); 586 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { 587 return f; 588 } 589 } catch (final NumberFormatException nfe) { // NOPMD 590 // ignore the bad number 591 } 592 try { 593 final Double d = createDouble(str); 594 if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { 595 return d; 596 } 597 } catch (final NumberFormatException nfe) { // NOPMD 598 // ignore the bad number 599 } 600 601 return createBigDecimal(str); 602 603 } 604 } 605 } 606 607 /** 608 * <p>Utility method for {@link #createNumber(java.lang.String)}.</p> 609 * 610 * <p>Returns <code>true</code> if s is <code>null</code>.</p> 611 * 612 * @param str the String to check 613 * @return if it is all zeros or <code>null</code> 614 */ 615 private static boolean isAllZeros(final String str) { 616 if (str == null) { 617 return true; 618 } 619 for (int i = str.length() - 1; i >= 0; i--) { 620 if (str.charAt(i) != '0') { 621 return false; 622 } 623 } 624 return str.length() > 0; 625 } 626 627 //----------------------------------------------------------------------- 628 /** 629 * <p>Convert a <code>String</code> to a <code>Float</code>.</p> 630 * 631 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 632 * 633 * @param str a <code>String</code> to convert, may be null 634 * @return converted <code>Float</code> (or null if the input is null) 635 * @throws NumberFormatException if the value cannot be converted 636 */ 637 public static Float createFloat(final String str) { 638 if (str == null) { 639 return null; 640 } 641 return Float.valueOf(str); 642 } 643 644 /** 645 * <p>Convert a <code>String</code> to a <code>Double</code>.</p> 646 * 647 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 648 * 649 * @param str a <code>String</code> to convert, may be null 650 * @return converted <code>Double</code> (or null if the input is null) 651 * @throws NumberFormatException if the value cannot be converted 652 */ 653 public static Double createDouble(final String str) { 654 if (str == null) { 655 return null; 656 } 657 return Double.valueOf(str); 658 } 659 660 /** 661 * <p>Convert a <code>String</code> to a <code>Integer</code>, handling 662 * hex and octal notations.</p> 663 * 664 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 665 * 666 * @param str a <code>String</code> to convert, may be null 667 * @return converted <code>Integer</code> (or null if the input is null) 668 * @throws NumberFormatException if the value cannot be converted 669 */ 670 public static Integer createInteger(final String str) { 671 if (str == null) { 672 return null; 673 } 674 // decode() handles 0xAABD and 0777 (hex and octal) as well. 675 return Integer.decode(str); 676 } 677 678 /** 679 * <p>Convert a <code>String</code> to a <code>Long</code>; 680 * since 3.1 it handles 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>Long</code> (or null if the input is null) 686 * @throws NumberFormatException if the value cannot be converted 687 */ 688 public static Long createLong(final String str) { 689 if (str == null) { 690 return null; 691 } 692 return Long.decode(str); 693 } 694 695 /** 696 * <p>Convert a <code>String</code> to a <code>BigInteger</code>; 697 * since 3.2 it handles hex (0x or #) and octal (0) notations.</p> 698 * 699 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 700 * 701 * @param str a <code>String</code> to convert, may be null 702 * @return converted <code>BigInteger</code> (or null if the input is null) 703 * @throws NumberFormatException if the value cannot be converted 704 */ 705 public static BigInteger createBigInteger(final String str) { 706 if (str == null) { 707 return null; 708 } 709 int pos = 0; // offset within string 710 int radix = 10; 711 boolean negate = false; // need to negate later? 712 if (str.startsWith("-")) { 713 negate = true; 714 pos = 1; 715 } 716 if (str.startsWith("0x", pos) || str.startsWith("0x", pos)) { // hex 717 radix = 16; 718 pos += 2; 719 } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) 720 radix = 16; 721 pos ++; 722 } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits 723 radix = 8; 724 pos ++; 725 } // default is to treat as decimal 726 727 final BigInteger value = new BigInteger(str.substring(pos), radix); 728 return negate ? value.negate() : value; 729 } 730 731 /** 732 * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p> 733 * 734 * <p>Returns <code>null</code> if the string is <code>null</code>.</p> 735 * 736 * @param str a <code>String</code> to convert, may be null 737 * @return converted <code>BigDecimal</code> (or null if the input is null) 738 * @throws NumberFormatException if the value cannot be converted 739 */ 740 public static BigDecimal createBigDecimal(final String str) { 741 if (str == null) { 742 return null; 743 } 744 // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException 745 if (StringUtils.isBlank(str)) { 746 throw new NumberFormatException("A blank string is not a valid number"); 747 } 748 if (str.trim().startsWith("--")) { 749 // this is protection for poorness in java.lang.BigDecimal. 750 // it accepts this as a legal value, but it does not appear 751 // to be in specification of class. OS X Java parses it to 752 // a wrong value. 753 throw new NumberFormatException(str + " is not a valid number."); 754 } 755 return new BigDecimal(str); 756 } 757 758 // Min in array 759 //-------------------------------------------------------------------- 760 /** 761 * <p>Returns the minimum value in an array.</p> 762 * 763 * @param array an array, must not be null or empty 764 * @return the minimum value in the array 765 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 766 * @throws IllegalArgumentException if <code>array</code> is empty 767 */ 768 public static long min(final long[] array) { 769 // Validates input 770 validateArray(array); 771 772 // Finds and returns min 773 long min = array[0]; 774 for (int i = 1; i < array.length; i++) { 775 if (array[i] < min) { 776 min = array[i]; 777 } 778 } 779 780 return min; 781 } 782 783 /** 784 * <p>Returns the minimum value in an array.</p> 785 * 786 * @param array an array, must not be null or empty 787 * @return the minimum value in the array 788 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 789 * @throws IllegalArgumentException if <code>array</code> is empty 790 */ 791 public static int min(final int[] array) { 792 // Validates input 793 validateArray(array); 794 795 // Finds and returns min 796 int min = array[0]; 797 for (int j = 1; j < array.length; j++) { 798 if (array[j] < min) { 799 min = array[j]; 800 } 801 } 802 803 return min; 804 } 805 806 /** 807 * <p>Returns the minimum value in an array.</p> 808 * 809 * @param array an array, must not be null or empty 810 * @return the minimum value in the array 811 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 812 * @throws IllegalArgumentException if <code>array</code> is empty 813 */ 814 public static short min(final short[] array) { 815 // Validates input 816 validateArray(array); 817 818 // Finds and returns min 819 short min = array[0]; 820 for (int i = 1; i < array.length; i++) { 821 if (array[i] < min) { 822 min = array[i]; 823 } 824 } 825 826 return min; 827 } 828 829 /** 830 * <p>Returns the minimum value in an array.</p> 831 * 832 * @param array an array, must not be null or empty 833 * @return the minimum value in the array 834 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 835 * @throws IllegalArgumentException if <code>array</code> is empty 836 */ 837 public static byte min(final byte[] array) { 838 // Validates input 839 validateArray(array); 840 841 // Finds and returns min 842 byte min = array[0]; 843 for (int i = 1; i < array.length; i++) { 844 if (array[i] < min) { 845 min = array[i]; 846 } 847 } 848 849 return min; 850 } 851 852 /** 853 * <p>Returns the minimum value in an array.</p> 854 * 855 * @param array an array, must not be null or empty 856 * @return the minimum value in the array 857 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 858 * @throws IllegalArgumentException if <code>array</code> is empty 859 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently 860 */ 861 public static double min(final double[] array) { 862 // Validates input 863 validateArray(array); 864 865 // Finds and returns min 866 double min = array[0]; 867 for (int i = 1; i < array.length; i++) { 868 if (Double.isNaN(array[i])) { 869 return Double.NaN; 870 } 871 if (array[i] < min) { 872 min = array[i]; 873 } 874 } 875 876 return min; 877 } 878 879 /** 880 * <p>Returns the minimum value in an array.</p> 881 * 882 * @param array an array, must not be null or empty 883 * @return the minimum value in the array 884 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 885 * @throws IllegalArgumentException if <code>array</code> is empty 886 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently 887 */ 888 public static float min(final float[] array) { 889 // Validates input 890 validateArray(array); 891 892 // Finds and returns min 893 float min = array[0]; 894 for (int i = 1; i < array.length; i++) { 895 if (Float.isNaN(array[i])) { 896 return Float.NaN; 897 } 898 if (array[i] < min) { 899 min = array[i]; 900 } 901 } 902 903 return min; 904 } 905 906 // Max in array 907 //-------------------------------------------------------------------- 908 /** 909 * <p>Returns the maximum value in an array.</p> 910 * 911 * @param array an array, must not be null or empty 912 * @return the minimum value in the array 913 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 914 * @throws IllegalArgumentException if <code>array</code> is empty 915 */ 916 public static long max(final long[] array) { 917 // Validates input 918 validateArray(array); 919 920 // Finds and returns max 921 long max = array[0]; 922 for (int j = 1; j < array.length; j++) { 923 if (array[j] > max) { 924 max = array[j]; 925 } 926 } 927 928 return max; 929 } 930 931 /** 932 * <p>Returns the maximum value in an array.</p> 933 * 934 * @param array an array, must not be null or empty 935 * @return the minimum value in the array 936 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 937 * @throws IllegalArgumentException if <code>array</code> is empty 938 */ 939 public static int max(final int[] array) { 940 // Validates input 941 validateArray(array); 942 943 // Finds and returns max 944 int max = array[0]; 945 for (int j = 1; j < array.length; j++) { 946 if (array[j] > max) { 947 max = array[j]; 948 } 949 } 950 951 return max; 952 } 953 954 /** 955 * <p>Returns the maximum value in an array.</p> 956 * 957 * @param array an array, must not be null or empty 958 * @return the minimum value in the array 959 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 960 * @throws IllegalArgumentException if <code>array</code> is empty 961 */ 962 public static short max(final short[] array) { 963 // Validates input 964 validateArray(array); 965 966 // Finds and returns max 967 short max = array[0]; 968 for (int i = 1; i < array.length; i++) { 969 if (array[i] > max) { 970 max = array[i]; 971 } 972 } 973 974 return max; 975 } 976 977 /** 978 * <p>Returns the maximum value in an array.</p> 979 * 980 * @param array an array, must not be null or empty 981 * @return the minimum value in the array 982 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 983 * @throws IllegalArgumentException if <code>array</code> is empty 984 */ 985 public static byte max(final byte[] array) { 986 // Validates input 987 validateArray(array); 988 989 // Finds and returns max 990 byte max = array[0]; 991 for (int i = 1; i < array.length; i++) { 992 if (array[i] > max) { 993 max = array[i]; 994 } 995 } 996 997 return max; 998 } 999 1000 /** 1001 * <p>Returns the maximum value in an array.</p> 1002 * 1003 * @param array an array, must not be null or empty 1004 * @return the minimum value in the array 1005 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1006 * @throws IllegalArgumentException if <code>array</code> is empty 1007 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently 1008 */ 1009 public static double max(final double[] array) { 1010 // Validates input 1011 validateArray(array); 1012 1013 // Finds and returns max 1014 double max = array[0]; 1015 for (int j = 1; j < array.length; j++) { 1016 if (Double.isNaN(array[j])) { 1017 return Double.NaN; 1018 } 1019 if (array[j] > max) { 1020 max = array[j]; 1021 } 1022 } 1023 1024 return max; 1025 } 1026 1027 /** 1028 * <p>Returns the maximum value in an array.</p> 1029 * 1030 * @param array an array, must not be null or empty 1031 * @return the minimum value in the array 1032 * @throws IllegalArgumentException if <code>array</code> is <code>null</code> 1033 * @throws IllegalArgumentException if <code>array</code> is empty 1034 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently 1035 */ 1036 public static float max(final float[] array) { 1037 // Validates input 1038 validateArray(array); 1039 1040 // Finds and returns max 1041 float max = array[0]; 1042 for (int j = 1; j < array.length; j++) { 1043 if (Float.isNaN(array[j])) { 1044 return Float.NaN; 1045 } 1046 if (array[j] > max) { 1047 max = array[j]; 1048 } 1049 } 1050 1051 return max; 1052 } 1053 1054 /** 1055 * Checks if the specified array is neither null nor empty. 1056 * 1057 * @param array the array to check 1058 * @throws IllegalArgumentException if {@code array} is either {@code null} or empty 1059 */ 1060 private static void validateArray(final Object array) { 1061 if (array == null) { 1062 throw new IllegalArgumentException("The Array must not be null"); 1063 } else if (Array.getLength(array) == 0) { 1064 throw new IllegalArgumentException("Array cannot be empty."); 1065 } 1066 } 1067 1068 // 3 param min 1069 //----------------------------------------------------------------------- 1070 /** 1071 * <p>Gets the minimum of three <code>long</code> values.</p> 1072 * 1073 * @param a value 1 1074 * @param b value 2 1075 * @param c value 3 1076 * @return the smallest of the values 1077 */ 1078 public static long min(long a, final long b, final long c) { 1079 if (b < a) { 1080 a = b; 1081 } 1082 if (c < a) { 1083 a = c; 1084 } 1085 return a; 1086 } 1087 1088 /** 1089 * <p>Gets the minimum of three <code>int</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 int min(int a, final int b, final int 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>short</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 short min(short a, final short b, final short 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>byte</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 byte min(byte a, final byte b, final byte 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>double</code> values.</p> 1144 * 1145 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1146 * returned. Infinity is handled.</p> 1147 * 1148 * @param a value 1 1149 * @param b value 2 1150 * @param c value 3 1151 * @return the smallest of the values 1152 * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently 1153 */ 1154 public static double min(final double a, final double b, final double c) { 1155 return Math.min(Math.min(a, b), c); 1156 } 1157 1158 /** 1159 * <p>Gets the minimum of three <code>float</code> values.</p> 1160 * 1161 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1162 * returned. Infinity is handled.</p> 1163 * 1164 * @param a value 1 1165 * @param b value 2 1166 * @param c value 3 1167 * @return the smallest of the values 1168 * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently 1169 */ 1170 public static float min(final float a, final float b, final float c) { 1171 return Math.min(Math.min(a, b), c); 1172 } 1173 1174 // 3 param max 1175 //----------------------------------------------------------------------- 1176 /** 1177 * <p>Gets the maximum of three <code>long</code> values.</p> 1178 * 1179 * @param a value 1 1180 * @param b value 2 1181 * @param c value 3 1182 * @return the largest of the values 1183 */ 1184 public static long max(long a, final long b, final long c) { 1185 if (b > a) { 1186 a = b; 1187 } 1188 if (c > a) { 1189 a = c; 1190 } 1191 return a; 1192 } 1193 1194 /** 1195 * <p>Gets the maximum of three <code>int</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 int max(int a, final int b, final int 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>short</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 short max(short a, final short b, final short 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>byte</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 byte max(byte a, final byte b, final byte 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>double</code> values.</p> 1250 * 1251 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1252 * returned. Infinity is handled.</p> 1253 * 1254 * @param a value 1 1255 * @param b value 2 1256 * @param c value 3 1257 * @return the largest of the values 1258 * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently 1259 */ 1260 public static double max(final double a, final double b, final double c) { 1261 return Math.max(Math.max(a, b), c); 1262 } 1263 1264 /** 1265 * <p>Gets the maximum of three <code>float</code> values.</p> 1266 * 1267 * <p>If any value is <code>NaN</code>, <code>NaN</code> is 1268 * returned. Infinity is handled.</p> 1269 * 1270 * @param a value 1 1271 * @param b value 2 1272 * @param c value 3 1273 * @return the largest of the values 1274 * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently 1275 */ 1276 public static float max(final float a, final float b, final float c) { 1277 return Math.max(Math.max(a, b), c); 1278 } 1279 1280 //----------------------------------------------------------------------- 1281 /** 1282 * <p>Checks whether the <code>String</code> contains only 1283 * digit characters.</p> 1284 * 1285 * <p><code>Null</code> and empty String will return 1286 * <code>false</code>.</p> 1287 * 1288 * @param str the <code>String</code> to check 1289 * @return <code>true</code> if str contains only Unicode numeric 1290 */ 1291 public static boolean isDigits(final String str) { 1292 if (StringUtils.isEmpty(str)) { 1293 return false; 1294 } 1295 for (int i = 0; i < str.length(); i++) { 1296 if (!Character.isDigit(str.charAt(i))) { 1297 return false; 1298 } 1299 } 1300 return true; 1301 } 1302 1303 /** 1304 * <p>Checks whether the String a valid Java number.</p> 1305 * 1306 * <p>Valid numbers include hexadecimal marked with the <code>0x</code> 1307 * qualifier, scientific notation and numbers marked with a type 1308 * qualifier (e.g. 123L).</p> 1309 * 1310 * <p><code>Null</code> and empty String will return 1311 * <code>false</code>.</p> 1312 * 1313 * @param str the <code>String</code> to check 1314 * @return <code>true</code> if the string is a correctly formatted number 1315 */ 1316 public static boolean isNumber(final String str) { 1317 if (StringUtils.isEmpty(str)) { 1318 return false; 1319 } 1320 final char[] chars = str.toCharArray(); 1321 int sz = chars.length; 1322 boolean hasExp = false; 1323 boolean hasDecPoint = false; 1324 boolean allowSigns = false; 1325 boolean foundDigit = false; 1326 // deal with any possible sign up front 1327 final int start = (chars[0] == '-') ? 1 : 0; 1328 if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') { 1329 int i = start + 2; 1330 if (i == sz) { 1331 return false; // str == "0x" 1332 } 1333 // checking hex (it can't be anything else) 1334 for (; i < chars.length; i++) { 1335 if ((chars[i] < '0' || chars[i] > '9') 1336 && (chars[i] < 'a' || chars[i] > 'f') 1337 && (chars[i] < 'A' || chars[i] > 'F')) { 1338 return false; 1339 } 1340 } 1341 return true; 1342 } 1343 sz--; // don't want to loop to the last char, check it afterwords 1344 // for type qualifiers 1345 int i = start; 1346 // loop to the next to last char or to the last char if we need another digit to 1347 // make a valid number (e.g. chars[0..5] = "1234E") 1348 while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { 1349 if (chars[i] >= '0' && chars[i] <= '9') { 1350 foundDigit = true; 1351 allowSigns = false; 1352 1353 } else if (chars[i] == '.') { 1354 if (hasDecPoint || hasExp) { 1355 // two decimal points or dec in exponent 1356 return false; 1357 } 1358 hasDecPoint = true; 1359 } else if (chars[i] == 'e' || chars[i] == 'E') { 1360 // we've already taken care of hex. 1361 if (hasExp) { 1362 // two E's 1363 return false; 1364 } 1365 if (!foundDigit) { 1366 return false; 1367 } 1368 hasExp = true; 1369 allowSigns = true; 1370 } else if (chars[i] == '+' || chars[i] == '-') { 1371 if (!allowSigns) { 1372 return false; 1373 } 1374 allowSigns = false; 1375 foundDigit = false; // we need a digit after the E 1376 } else { 1377 return false; 1378 } 1379 i++; 1380 } 1381 if (i < chars.length) { 1382 if (chars[i] >= '0' && chars[i] <= '9') { 1383 // no type qualifier, OK 1384 return true; 1385 } 1386 if (chars[i] == 'e' || chars[i] == 'E') { 1387 // can't have an E at the last byte 1388 return false; 1389 } 1390 if (chars[i] == '.') { 1391 if (hasDecPoint || hasExp) { 1392 // two decimal points or dec in exponent 1393 return false; 1394 } 1395 // single trailing decimal point after non-exponent is ok 1396 return foundDigit; 1397 } 1398 if (!allowSigns 1399 && (chars[i] == 'd' 1400 || chars[i] == 'D' 1401 || chars[i] == 'f' 1402 || chars[i] == 'F')) { 1403 return foundDigit; 1404 } 1405 if (chars[i] == 'l' 1406 || chars[i] == 'L') { 1407 // not allowing L with an exponent or decimal point 1408 return foundDigit && !hasExp && !hasDecPoint; 1409 } 1410 // last character is illegal 1411 return false; 1412 } 1413 // allowSigns is true iff the val ends in 'E' 1414 // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass 1415 return !allowSigns && foundDigit; 1416 } 1417 1418}