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 * @author Apache Software Foundation
028 * @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
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 916081 2010-02-25 01:28:13Z niallp $
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 = Byte.valueOf((byte) 0);
060 /** Reusable Byte constant for one. */
061 public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);
062 /** Reusable Byte constant for minus one. */
063 public static final Byte BYTE_MINUS_ONE = Byte.valueOf((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.toInt("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.toInt(null) = 0
097 * NumberUtils.toInt("") = 0
098 * NumberUtils.toInt("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 * @since 2.1
105 */
106 public static int toInt(String str) {
107 return toInt(str, 0);
108 }
109
110 /**
111 * <p>Convert a <code>String</code> to an <code>int</code>, returning a
112 * default value if the conversion fails.</p>
113 *
114 * <p>If the string is <code>null</code>, the default value is returned.</p>
115 *
116 * <pre>
117 * NumberUtils.toInt(null, 1) = 1
118 * NumberUtils.toInt("", 1) = 1
119 * NumberUtils.toInt("1", 0) = 1
120 * </pre>
121 *
122 * @param str the string to convert, may be null
123 * @param defaultValue the default value
124 * @return the int represented by the string, or the default if conversion fails
125 * @since 2.1
126 */
127 public static int toInt(String str, int defaultValue) {
128 if(str == null) {
129 return defaultValue;
130 }
131 try {
132 return Integer.parseInt(str);
133 } catch (NumberFormatException nfe) {
134 return defaultValue;
135 }
136 }
137
138 /**
139 * <p>Convert a <code>String</code> to a <code>long</code>, returning
140 * <code>zero</code> if the conversion fails.</p>
141 *
142 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
143 *
144 * <pre>
145 * NumberUtils.toLong(null) = 0L
146 * NumberUtils.toLong("") = 0L
147 * NumberUtils.toLong("1") = 1L
148 * </pre>
149 *
150 * @param str the string to convert, may be null
151 * @return the long represented by the string, or <code>0</code> if
152 * conversion fails
153 * @since 2.1
154 */
155 public static long toLong(String str) {
156 return toLong(str, 0L);
157 }
158
159 /**
160 * <p>Convert a <code>String</code> to a <code>long</code>, returning a
161 * default value if the conversion fails.</p>
162 *
163 * <p>If the string is <code>null</code>, the default value is returned.</p>
164 *
165 * <pre>
166 * NumberUtils.toLong(null, 1L) = 1L
167 * NumberUtils.toLong("", 1L) = 1L
168 * NumberUtils.toLong("1", 0L) = 1L
169 * </pre>
170 *
171 * @param str the string to convert, may be null
172 * @param defaultValue the default value
173 * @return the long represented by the string, or the default if conversion fails
174 * @since 2.1
175 */
176 public static long toLong(String str, long defaultValue) {
177 if (str == null) {
178 return defaultValue;
179 }
180 try {
181 return Long.parseLong(str);
182 } catch (NumberFormatException nfe) {
183 return defaultValue;
184 }
185 }
186
187 /**
188 * <p>Convert a <code>String</code> to a <code>float</code>, returning
189 * <code>0.0f</code> if the conversion fails.</p>
190 *
191 * <p>If the string <code>str</code> is <code>null</code>,
192 * <code>0.0f</code> is returned.</p>
193 *
194 * <pre>
195 * NumberUtils.toFloat(null) = 0.0f
196 * NumberUtils.toFloat("") = 0.0f
197 * NumberUtils.toFloat("1.5") = 1.5f
198 * </pre>
199 *
200 * @param str the string to convert, may be <code>null</code>
201 * @return the float represented by the string, or <code>0.0f</code>
202 * if conversion fails
203 * @since 2.1
204 */
205 public static float toFloat(String str) {
206 return toFloat(str, 0.0f);
207 }
208
209 /**
210 * <p>Convert a <code>String</code> to a <code>float</code>, returning a
211 * default value if the conversion fails.</p>
212 *
213 * <p>If the string <code>str</code> is <code>null</code>, the default
214 * value is returned.</p>
215 *
216 * <pre>
217 * NumberUtils.toFloat(null, 1.1f) = 1.0f
218 * NumberUtils.toFloat("", 1.1f) = 1.1f
219 * NumberUtils.toFloat("1.5", 0.0f) = 1.5f
220 * </pre>
221 *
222 * @param str the string to convert, may be <code>null</code>
223 * @param defaultValue the default value
224 * @return the float represented by the string, or defaultValue
225 * if conversion fails
226 * @since 2.1
227 */
228 public static float toFloat(String str, float defaultValue) {
229 if (str == null) {
230 return defaultValue;
231 }
232 try {
233 return Float.parseFloat(str);
234 } catch (NumberFormatException nfe) {
235 return defaultValue;
236 }
237 }
238
239 /**
240 * <p>Convert a <code>String</code> to a <code>double</code>, returning
241 * <code>0.0d</code> if the conversion fails.</p>
242 *
243 * <p>If the string <code>str</code> is <code>null</code>,
244 * <code>0.0d</code> is returned.</p>
245 *
246 * <pre>
247 * NumberUtils.toDouble(null) = 0.0d
248 * NumberUtils.toDouble("") = 0.0d
249 * NumberUtils.toDouble("1.5") = 1.5d
250 * </pre>
251 *
252 * @param str the string to convert, may be <code>null</code>
253 * @return the double represented by the string, or <code>0.0d</code>
254 * if conversion fails
255 * @since 2.1
256 */
257 public static double toDouble(String str) {
258 return toDouble(str, 0.0d);
259 }
260
261 /**
262 * <p>Convert a <code>String</code> to a <code>double</code>, returning a
263 * default value if the conversion fails.</p>
264 *
265 * <p>If the string <code>str</code> is <code>null</code>, the default
266 * value is returned.</p>
267 *
268 * <pre>
269 * NumberUtils.toDouble(null, 1.1d) = 1.1d
270 * NumberUtils.toDouble("", 1.1d) = 1.1d
271 * NumberUtils.toDouble("1.5", 0.0d) = 1.5d
272 * </pre>
273 *
274 * @param str the string to convert, may be <code>null</code>
275 * @param defaultValue the default value
276 * @return the double represented by the string, or defaultValue
277 * if conversion fails
278 * @since 2.1
279 */
280 public static double toDouble(String str, double defaultValue) {
281 if (str == null) {
282 return defaultValue;
283 }
284 try {
285 return Double.parseDouble(str);
286 } catch (NumberFormatException nfe) {
287 return defaultValue;
288 }
289 }
290
291 //-----------------------------------------------------------------------
292 /**
293 * <p>Convert a <code>String</code> to a <code>byte</code>, returning
294 * <code>zero</code> if the conversion fails.</p>
295 *
296 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
297 *
298 * <pre>
299 * NumberUtils.toByte(null) = 0
300 * NumberUtils.toByte("") = 0
301 * NumberUtils.toByte("1") = 1
302 * </pre>
303 *
304 * @param str the string to convert, may be null
305 * @return the byte represented by the string, or <code>zero</code> if
306 * conversion fails
307 * @since 2.5
308 */
309 public static byte toByte(String str) {
310 return toByte(str, (byte) 0);
311 }
312
313 /**
314 * <p>Convert a <code>String</code> to a <code>byte</code>, returning a
315 * default value if the conversion fails.</p>
316 *
317 * <p>If the string is <code>null</code>, the default value is returned.</p>
318 *
319 * <pre>
320 * NumberUtils.toByte(null, 1) = 1
321 * NumberUtils.toByte("", 1) = 1
322 * NumberUtils.toByte("1", 0) = 1
323 * </pre>
324 *
325 * @param str the string to convert, may be null
326 * @param defaultValue the default value
327 * @return the byte represented by the string, or the default if conversion fails
328 * @since 2.5
329 */
330 public static byte toByte(String str, byte defaultValue) {
331 if(str == null) {
332 return defaultValue;
333 }
334 try {
335 return Byte.parseByte(str);
336 } catch (NumberFormatException nfe) {
337 return defaultValue;
338 }
339 }
340
341 /**
342 * <p>Convert a <code>String</code> to a <code>short</code>, returning
343 * <code>zero</code> if the conversion fails.</p>
344 *
345 * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
346 *
347 * <pre>
348 * NumberUtils.toShort(null) = 0
349 * NumberUtils.toShort("") = 0
350 * NumberUtils.toShort("1") = 1
351 * </pre>
352 *
353 * @param str the string to convert, may be null
354 * @return the short represented by the string, or <code>zero</code> if
355 * conversion fails
356 * @since 2.5
357 */
358 public static short toShort(String str) {
359 return toShort(str, (short) 0);
360 }
361
362 /**
363 * <p>Convert a <code>String</code> to an <code>short</code>, returning a
364 * default value if the conversion fails.</p>
365 *
366 * <p>If the string is <code>null</code>, the default value is returned.</p>
367 *
368 * <pre>
369 * NumberUtils.toShort(null, 1) = 1
370 * NumberUtils.toShort("", 1) = 1
371 * NumberUtils.toShort("1", 0) = 1
372 * </pre>
373 *
374 * @param str the string to convert, may be null
375 * @param defaultValue the default value
376 * @return the short represented by the string, or the default if conversion fails
377 * @since 2.5
378 */
379 public static short toShort(String str, short defaultValue) {
380 if(str == null) {
381 return defaultValue;
382 }
383 try {
384 return Short.parseShort(str);
385 } catch (NumberFormatException nfe) {
386 return defaultValue;
387 }
388 }
389
390 //-----------------------------------------------------------------------
391 // must handle Long, Float, Integer, Float, Short,
392 // BigDecimal, BigInteger and Byte
393 // useful methods:
394 // Byte.decode(String)
395 // Byte.valueOf(String,int radix)
396 // Byte.valueOf(String)
397 // Double.valueOf(String)
398 // Float.valueOf(String)
399 // new Float(String)
400 // Integer.valueOf(String,int radix)
401 // Integer.valueOf(String)
402 // Integer.decode(String)
403 // Integer.getInteger(String)
404 // Integer.getInteger(String,int val)
405 // Integer.getInteger(String,Integer val)
406 // new Integer(String)
407 // new Double(String)
408 // new Byte(String)
409 // new Long(String)
410 // Long.getLong(String)
411 // Long.getLong(String,int)
412 // Long.getLong(String,Integer)
413 // Long.valueOf(String,int)
414 // Long.valueOf(String)
415 // new Short(String)
416 // Short.decode(String)
417 // Short.valueOf(String,int)
418 // Short.valueOf(String)
419 // new BigDecimal(String)
420 // new BigInteger(String)
421 // new BigInteger(String,int radix)
422 // Possible inputs:
423 // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
424 // plus minus everything. Prolly more. A lot are not separable.
425
426 /**
427 * <p>Turns a string value into a java.lang.Number.</p>
428 *
429 * <p>First, the value is examined for a type qualifier on the end
430 * (<code>'f','F','d','D','l','L'</code>). If it is found, it starts
431 * trying to create successively larger types from the type specified
432 * until one is found that can represent the value.</p>
433 *
434 * <p>If a type specifier is not found, it will check for a decimal point
435 * and then try successively larger types from <code>Integer</code> to
436 * <code>BigInteger</code> and from <code>Float</code> to
437 * <code>BigDecimal</code>.</p>
438 *
439 * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
440 * will be interpreted as a hexadecimal integer. Values with leading
441 * <code>0</code>'s will not be interpreted as octal.</p>
442 *
443 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
444 *
445 * <p>This method does not trim the input string, i.e., strings with leading
446 * or trailing spaces will generate NumberFormatExceptions.</p>
447 *
448 * @param str String containing a number, may be null
449 * @return Number created from the string
450 * @throws NumberFormatException if the value cannot be converted
451 */
452 public static Number createNumber(String str) throws NumberFormatException {
453 if (str == null) {
454 return null;
455 }
456 if (StringUtils.isBlank(str)) {
457 throw new NumberFormatException("A blank string is not a valid number");
458 }
459 if (str.startsWith("--")) {
460 // this is protection for poorness in java.lang.BigDecimal.
461 // it accepts this as a legal value, but it does not appear
462 // to be in specification of class. OS X Java parses it to
463 // a wrong value.
464 return null;
465 }
466 if (str.startsWith("0x") || str.startsWith("-0x")) {
467 return createInteger(str);
468 }
469 char lastChar = str.charAt(str.length() - 1);
470 String mant;
471 String dec;
472 String exp;
473 int decPos = str.indexOf('.');
474 int expPos = str.indexOf('e') + str.indexOf('E') + 1;
475
476 if (decPos > -1) {
477
478 if (expPos > -1) {
479 if (expPos < decPos) {
480 throw new NumberFormatException(str + " is not a valid number.");
481 }
482 dec = str.substring(decPos + 1, expPos);
483 } else {
484 dec = str.substring(decPos + 1);
485 }
486 mant = str.substring(0, decPos);
487 } else {
488 if (expPos > -1) {
489 mant = str.substring(0, expPos);
490 } else {
491 mant = str;
492 }
493 dec = null;
494 }
495 if (!Character.isDigit(lastChar) && lastChar != '.') {
496 if (expPos > -1 && expPos < str.length() - 1) {
497 exp = str.substring(expPos + 1, str.length() - 1);
498 } else {
499 exp = null;
500 }
501 //Requesting a specific type..
502 String numeric = str.substring(0, str.length() - 1);
503 boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
504 switch (lastChar) {
505 case 'l' :
506 case 'L' :
507 if (dec == null
508 && exp == null
509 && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
510 try {
511 return createLong(numeric);
512 } catch (NumberFormatException nfe) {
513 //Too big for a long
514 }
515 return createBigInteger(numeric);
516
517 }
518 throw new NumberFormatException(str + " is not a valid number.");
519 case 'f' :
520 case 'F' :
521 try {
522 Float f = NumberUtils.createFloat(numeric);
523 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
524 //If it's too big for a float or the float value = 0 and the string
525 //has non-zeros in it, then float does not have the precision we want
526 return f;
527 }
528
529 } catch (NumberFormatException nfe) {
530 // ignore the bad number
531 }
532 //$FALL-THROUGH$
533 case 'd' :
534 case 'D' :
535 try {
536 Double d = NumberUtils.createDouble(numeric);
537 if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
538 return d;
539 }
540 } catch (NumberFormatException nfe) {
541 // ignore the bad number
542 }
543 try {
544 return createBigDecimal(numeric);
545 } catch (NumberFormatException e) {
546 // ignore the bad number
547 }
548 //$FALL-THROUGH$
549 default :
550 throw new NumberFormatException(str + " is not a valid number.");
551
552 }
553 } else {
554 //User doesn't have a preference on the return type, so let's start
555 //small and go from there...
556 if (expPos > -1 && expPos < str.length() - 1) {
557 exp = str.substring(expPos + 1, str.length());
558 } else {
559 exp = null;
560 }
561 if (dec == null && exp == null) {
562 //Must be an int,long,bigint
563 try {
564 return createInteger(str);
565 } catch (NumberFormatException nfe) {
566 // ignore the bad number
567 }
568 try {
569 return createLong(str);
570 } catch (NumberFormatException nfe) {
571 // ignore the bad number
572 }
573 return createBigInteger(str);
574
575 } else {
576 //Must be a float,double,BigDec
577 boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
578 try {
579 Float f = createFloat(str);
580 if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
581 return f;
582 }
583 } catch (NumberFormatException nfe) {
584 // ignore the bad number
585 }
586 try {
587 Double d = createDouble(str);
588 if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
589 return d;
590 }
591 } catch (NumberFormatException nfe) {
592 // ignore the bad number
593 }
594
595 return createBigDecimal(str);
596
597 }
598 }
599 }
600
601 /**
602 * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
603 *
604 * <p>Returns <code>true</code> if s is <code>null</code>.</p>
605 *
606 * @param str the String to check
607 * @return if it is all zeros or <code>null</code>
608 */
609 private static boolean isAllZeros(String str) {
610 if (str == null) {
611 return true;
612 }
613 for (int i = str.length() - 1; i >= 0; i--) {
614 if (str.charAt(i) != '0') {
615 return false;
616 }
617 }
618 return str.length() > 0;
619 }
620
621 //-----------------------------------------------------------------------
622 /**
623 * <p>Convert a <code>String</code> to a <code>Float</code>.</p>
624 *
625 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
626 *
627 * @param str a <code>String</code> to convert, may be null
628 * @return converted <code>Float</code>
629 * @throws NumberFormatException if the value cannot be converted
630 */
631 public static Float createFloat(String str) {
632 if (str == null) {
633 return null;
634 }
635 return Float.valueOf(str);
636 }
637
638 /**
639 * <p>Convert a <code>String</code> to a <code>Double</code>.</p>
640 *
641 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
642 *
643 * @param str a <code>String</code> to convert, may be null
644 * @return converted <code>Double</code>
645 * @throws NumberFormatException if the value cannot be converted
646 */
647 public static Double createDouble(String str) {
648 if (str == null) {
649 return null;
650 }
651 return Double.valueOf(str);
652 }
653
654 /**
655 * <p>Convert a <code>String</code> to a <code>Integer</code>, handling
656 * hex and octal notations.</p>
657 *
658 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
659 *
660 * @param str a <code>String</code> to convert, may be null
661 * @return converted <code>Integer</code>
662 * @throws NumberFormatException if the value cannot be converted
663 */
664 public static Integer createInteger(String str) {
665 if (str == null) {
666 return null;
667 }
668 // decode() handles 0xAABD and 0777 (hex and octal) as well.
669 return Integer.decode(str);
670 }
671
672 /**
673 * <p>Convert a <code>String</code> to a <code>Long</code>.</p>
674 *
675 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
676 *
677 * @param str a <code>String</code> to convert, may be null
678 * @return converted <code>Long</code>
679 * @throws NumberFormatException if the value cannot be converted
680 */
681 public static Long createLong(String str) {
682 if (str == null) {
683 return null;
684 }
685 return Long.valueOf(str);
686 }
687
688 /**
689 * <p>Convert a <code>String</code> to a <code>BigInteger</code>.</p>
690 *
691 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
692 *
693 * @param str a <code>String</code> to convert, may be null
694 * @return converted <code>BigInteger</code>
695 * @throws NumberFormatException if the value cannot be converted
696 */
697 public static BigInteger createBigInteger(String str) {
698 if (str == null) {
699 return null;
700 }
701 return new BigInteger(str);
702 }
703
704 /**
705 * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>
706 *
707 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
708 *
709 * @param str a <code>String</code> to convert, may be null
710 * @return converted <code>BigDecimal</code>
711 * @throws NumberFormatException if the value cannot be converted
712 */
713 public static BigDecimal createBigDecimal(String str) {
714 if (str == null) {
715 return null;
716 }
717 // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
718 if (StringUtils.isBlank(str)) {
719 throw new NumberFormatException("A blank string is not a valid number");
720 }
721 return new BigDecimal(str);
722 }
723
724 // Min in array
725 //--------------------------------------------------------------------
726 /**
727 * <p>Returns the minimum value in an array.</p>
728 *
729 * @param array an array, must not be null or empty
730 * @return the minimum value in the array
731 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
732 * @throws IllegalArgumentException if <code>array</code> is empty
733 */
734 public static long min(long[] array) {
735 // Validates input
736 if (array == null) {
737 throw new IllegalArgumentException("The Array must not be null");
738 } else if (array.length == 0) {
739 throw new IllegalArgumentException("Array cannot be empty.");
740 }
741
742 // Finds and returns min
743 long min = array[0];
744 for (int i = 1; i < array.length; i++) {
745 if (array[i] < min) {
746 min = array[i];
747 }
748 }
749
750 return min;
751 }
752
753 /**
754 * <p>Returns the minimum value in an array.</p>
755 *
756 * @param array an array, must not be null or empty
757 * @return the minimum value in the array
758 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
759 * @throws IllegalArgumentException if <code>array</code> is empty
760 */
761 public static int min(int[] array) {
762 // Validates input
763 if (array == null) {
764 throw new IllegalArgumentException("The Array must not be null");
765 } else if (array.length == 0) {
766 throw new IllegalArgumentException("Array cannot be empty.");
767 }
768
769 // Finds and returns min
770 int min = array[0];
771 for (int j = 1; j < array.length; j++) {
772 if (array[j] < min) {
773 min = array[j];
774 }
775 }
776
777 return min;
778 }
779
780 /**
781 * <p>Returns the minimum value in an array.</p>
782 *
783 * @param array an array, must not be null or empty
784 * @return the minimum value in the array
785 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
786 * @throws IllegalArgumentException if <code>array</code> is empty
787 */
788 public static short min(short[] 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 short min = array[0];
798 for (int i = 1; i < array.length; i++) {
799 if (array[i] < min) {
800 min = array[i];
801 }
802 }
803
804 return min;
805 }
806
807 /**
808 * <p>Returns the minimum value in an array.</p>
809 *
810 * @param array an array, must not be null or empty
811 * @return the minimum value in the array
812 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
813 * @throws IllegalArgumentException if <code>array</code> is empty
814 */
815 public static byte min(byte[] array) {
816 // Validates input
817 if (array == null) {
818 throw new IllegalArgumentException("The Array must not be null");
819 } else if (array.length == 0) {
820 throw new IllegalArgumentException("Array cannot be empty.");
821 }
822
823 // Finds and returns min
824 byte min = array[0];
825 for (int i = 1; i < array.length; i++) {
826 if (array[i] < min) {
827 min = array[i];
828 }
829 }
830
831 return min;
832 }
833
834 /**
835 * <p>Returns the minimum value in an array.</p>
836 *
837 * @param array an array, must not be null or empty
838 * @return the minimum value in the array
839 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
840 * @throws IllegalArgumentException if <code>array</code> is empty
841 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
842 */
843 public static double min(double[] array) {
844 // Validates input
845 if (array == null) {
846 throw new IllegalArgumentException("The Array must not be null");
847 } else if (array.length == 0) {
848 throw new IllegalArgumentException("Array cannot be empty.");
849 }
850
851 // Finds and returns min
852 double min = array[0];
853 for (int i = 1; i < array.length; i++) {
854 if (Double.isNaN(array[i])) {
855 return Double.NaN;
856 }
857 if (array[i] < min) {
858 min = array[i];
859 }
860 }
861
862 return min;
863 }
864
865 /**
866 * <p>Returns the minimum value in an array.</p>
867 *
868 * @param array an array, must not be null or empty
869 * @return the minimum value in the array
870 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
871 * @throws IllegalArgumentException if <code>array</code> is empty
872 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
873 */
874 public static float min(float[] array) {
875 // Validates input
876 if (array == null) {
877 throw new IllegalArgumentException("The Array must not be null");
878 } else if (array.length == 0) {
879 throw new IllegalArgumentException("Array cannot be empty.");
880 }
881
882 // Finds and returns min
883 float min = array[0];
884 for (int i = 1; i < array.length; i++) {
885 if (Float.isNaN(array[i])) {
886 return Float.NaN;
887 }
888 if (array[i] < min) {
889 min = array[i];
890 }
891 }
892
893 return min;
894 }
895
896 // Max in array
897 //--------------------------------------------------------------------
898 /**
899 * <p>Returns the maximum value in an array.</p>
900 *
901 * @param array an array, must not be null or empty
902 * @return the minimum value in the array
903 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
904 * @throws IllegalArgumentException if <code>array</code> is empty
905 */
906 public static long max(long[] array) {
907 // Validates input
908 if (array == null) {
909 throw new IllegalArgumentException("The Array must not be null");
910 } else if (array.length == 0) {
911 throw new IllegalArgumentException("Array cannot be empty.");
912 }
913
914 // Finds and returns max
915 long max = array[0];
916 for (int j = 1; j < array.length; j++) {
917 if (array[j] > max) {
918 max = array[j];
919 }
920 }
921
922 return max;
923 }
924
925 /**
926 * <p>Returns the maximum value in an array.</p>
927 *
928 * @param array an array, must not be null or empty
929 * @return the minimum value in the array
930 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
931 * @throws IllegalArgumentException if <code>array</code> is empty
932 */
933 public static int max(int[] array) {
934 // Validates input
935 if (array == null) {
936 throw new IllegalArgumentException("The Array must not be null");
937 } else if (array.length == 0) {
938 throw new IllegalArgumentException("Array cannot be empty.");
939 }
940
941 // Finds and returns max
942 int max = array[0];
943 for (int j = 1; j < array.length; j++) {
944 if (array[j] > max) {
945 max = array[j];
946 }
947 }
948
949 return max;
950 }
951
952 /**
953 * <p>Returns the maximum value in an array.</p>
954 *
955 * @param array an array, must not be null or empty
956 * @return the minimum value in the array
957 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
958 * @throws IllegalArgumentException if <code>array</code> is empty
959 */
960 public static short max(short[] 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 short max = array[0];
970 for (int i = 1; i < array.length; i++) {
971 if (array[i] > max) {
972 max = array[i];
973 }
974 }
975
976 return max;
977 }
978
979 /**
980 * <p>Returns the maximum value in an array.</p>
981 *
982 * @param array an array, must not be null or empty
983 * @return the minimum value in the array
984 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
985 * @throws IllegalArgumentException if <code>array</code> is empty
986 */
987 public static byte max(byte[] array) {
988 // Validates input
989 if (array == null) {
990 throw new IllegalArgumentException("The Array must not be null");
991 } else if (array.length == 0) {
992 throw new IllegalArgumentException("Array cannot be empty.");
993 }
994
995 // Finds and returns max
996 byte max = array[0];
997 for (int i = 1; i < array.length; i++) {
998 if (array[i] > max) {
999 max = array[i];
1000 }
1001 }
1002
1003 return max;
1004 }
1005
1006 /**
1007 * <p>Returns the maximum value in an array.</p>
1008 *
1009 * @param array an array, must not be null or empty
1010 * @return the minimum value in the array
1011 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
1012 * @throws IllegalArgumentException if <code>array</code> is empty
1013 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
1014 */
1015 public static double max(double[] array) {
1016 // Validates input
1017 if (array== null) {
1018 throw new IllegalArgumentException("The Array must not be null");
1019 } else if (array.length == 0) {
1020 throw new IllegalArgumentException("Array cannot be empty.");
1021 }
1022
1023 // Finds and returns max
1024 double max = array[0];
1025 for (int j = 1; j < array.length; j++) {
1026 if (Double.isNaN(array[j])) {
1027 return Double.NaN;
1028 }
1029 if (array[j] > max) {
1030 max = array[j];
1031 }
1032 }
1033
1034 return max;
1035 }
1036
1037 /**
1038 * <p>Returns the maximum value in an array.</p>
1039 *
1040 * @param array an array, must not be null or empty
1041 * @return the minimum value in the array
1042 * @throws IllegalArgumentException if <code>array</code> is <code>null</code>
1043 * @throws IllegalArgumentException if <code>array</code> is empty
1044 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
1045 */
1046 public static float max(float[] array) {
1047 // Validates input
1048 if (array == null) {
1049 throw new IllegalArgumentException("The Array must not be null");
1050 } else if (array.length == 0) {
1051 throw new IllegalArgumentException("Array cannot be empty.");
1052 }
1053
1054 // Finds and returns max
1055 float max = array[0];
1056 for (int j = 1; j < array.length; j++) {
1057 if (Float.isNaN(array[j])) {
1058 return Float.NaN;
1059 }
1060 if (array[j] > max) {
1061 max = array[j];
1062 }
1063 }
1064
1065 return max;
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, long b, 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, int b, 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, short b, 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, byte b, 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(double a, double b, 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(float a, float b, 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, long b, 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, int b, 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, short b, 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, byte b, 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(double a, double b, 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(float a, float b, 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(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(String str) {
1317 if (StringUtils.isEmpty(str)) {
1318 return false;
1319 }
1320 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 int start = (chars[0] == '-') ? 1 : 0;
1328 if (sz > start + 1) {
1329 if (chars[start] == '0' && chars[start + 1] == 'x') {
1330 int i = start + 2;
1331 if (i == sz) {
1332 return false; // str == "0x"
1333 }
1334 // checking hex (it can't be anything else)
1335 for (; i < chars.length; i++) {
1336 if ((chars[i] < '0' || chars[i] > '9')
1337 && (chars[i] < 'a' || chars[i] > 'f')
1338 && (chars[i] < 'A' || chars[i] > 'F')) {
1339 return false;
1340 }
1341 }
1342 return true;
1343 }
1344 }
1345 sz--; // don't want to loop to the last char, check it afterwords
1346 // for type qualifiers
1347 int i = start;
1348 // loop to the next to last char or to the last char if we need another digit to
1349 // make a valid number (e.g. chars[0..5] = "1234E")
1350 while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
1351 if (chars[i] >= '0' && chars[i] <= '9') {
1352 foundDigit = true;
1353 allowSigns = false;
1354
1355 } else if (chars[i] == '.') {
1356 if (hasDecPoint || hasExp) {
1357 // two decimal points or dec in exponent
1358 return false;
1359 }
1360 hasDecPoint = true;
1361 } else if (chars[i] == 'e' || chars[i] == 'E') {
1362 // we've already taken care of hex.
1363 if (hasExp) {
1364 // two E's
1365 return false;
1366 }
1367 if (!foundDigit) {
1368 return false;
1369 }
1370 hasExp = true;
1371 allowSigns = true;
1372 } else if (chars[i] == '+' || chars[i] == '-') {
1373 if (!allowSigns) {
1374 return false;
1375 }
1376 allowSigns = false;
1377 foundDigit = false; // we need a digit after the E
1378 } else {
1379 return false;
1380 }
1381 i++;
1382 }
1383 if (i < chars.length) {
1384 if (chars[i] >= '0' && chars[i] <= '9') {
1385 // no type qualifier, OK
1386 return true;
1387 }
1388 if (chars[i] == 'e' || chars[i] == 'E') {
1389 // can't have an E at the last byte
1390 return false;
1391 }
1392 if (chars[i] == '.') {
1393 if (hasDecPoint || hasExp) {
1394 // two decimal points or dec in exponent
1395 return false;
1396 }
1397 // single trailing decimal point after non-exponent is ok
1398 return foundDigit;
1399 }
1400 if (!allowSigns
1401 && (chars[i] == 'd'
1402 || chars[i] == 'D'
1403 || chars[i] == 'f'
1404 || chars[i] == 'F')) {
1405 return foundDigit;
1406 }
1407 if (chars[i] == 'l'
1408 || chars[i] == 'L') {
1409 // not allowing L with an exponent
1410 return foundDigit && !hasExp;
1411 }
1412 // last character is illegal
1413 return false;
1414 }
1415 // allowSigns is true iff the val ends in 'E'
1416 // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
1417 return !allowSigns && foundDigit;
1418 }
1419
1420 }