commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From scolebou...@apache.org
Subject cvs commit: jakarta-commons-sandbox/lang/src/java/org/apache/commons/lang Numbers.java
Date Mon, 01 Jul 2002 23:40:25 GMT
scolebourne    2002/07/01 16:40:25

  Modified:    lang/src/java/org/apache/commons/lang Numbers.java
  Log:
  Handle blank string in containsDigits
  Add maximum method
  Javadoc
  
  Revision  Changes    Path
  1.2       +365 -299  jakarta-commons-sandbox/lang/src/java/org/apache/commons/lang/Numbers.java
  
  Index: Numbers.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/lang/src/java/org/apache/commons/lang/Numbers.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- Numbers.java	22 Feb 2002 05:57:15 -0000	1.1
  +++ Numbers.java	1 Jul 2002 23:40:25 -0000	1.2
  @@ -1,299 +1,365 @@
  -package org.apache.commons.lang;
  -
  -/* ====================================================================
  - * The Apache Software License, Version 1.1
  - *
  - * Copyright (c) 2001 The Apache Software Foundation.  All rights
  - * reserved.
  - *
  - * Redistribution and use in source and binary forms, with or without
  - * modification, are permitted provided that the following conditions
  - * are met:
  - *
  - * 1. Redistributions of source code must retain the above copyright
  - *    notice, this list of conditions and the following disclaimer.
  - *
  - * 2. Redistributions in binary form must reproduce the above copyright
  - *    notice, this list of conditions and the following disclaimer in
  - *    the documentation and/or other materials provided with the
  - *    distribution.
  - *
  - * 3. The end-user documentation included with the redistribution,
  - *    if any, must include the following acknowledgment:
  - *       "This product includes software developed by the
  - *        Apache Software Foundation (http://www.apache.org/)."
  - *    Alternately, this acknowledgment may appear in the software itself,
  - *    if and wherever such third-party acknowledgments normally appear.
  - *
  - * 4. The names "Apache" and "Apache Software Foundation" and
  - *    "Apache Commons" must not be used to endorse or promote products
  - *    derived from this software without prior written permission. For
  - *    written permission, please contact apache@apache.org.
  - *
  - * 5. Products derived from this software may not be called "Apache",
  - *    "Apache Turbine", nor may "Apache" appear in their name, without
  - *    prior written permission of the Apache Software Foundation.
  - *
  - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  - * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  - * SUCH DAMAGE.
  - * ====================================================================
  - *
  - * This software consists of voluntary contributions made by many
  - * individuals on behalf of the Apache Software Foundation.  For more
  - * information on the Apache Software Foundation, please see
  - * <http://www.apache.org/>.
  - */
  -
  -import java.math.BigInteger;
  -import java.math.BigDecimal;
  -
  -/**
  - * Provides extra functionality for java Number classes.
  - *
  - * @author bayard@generationjava.com
  - * @version $Id$
  - */
  -final public class Numbers {
  -
  -    static public int stringToInt(String str) {
  -        return stringToInt(str,0);
  -    }
  -    static public int stringToInt(String str, int def) {
  -        try {
  -            return Integer.parseInt(str);
  -        } catch(NumberFormatException nfe) {
  -            return def;
  -        }
  -    }
  -
  -    // must handle Long, Float, Integer, Float, Short,
  -    //                  BigDecimal, BigInteger and Byte
  -    // useful methods:
  -    // Byte.decode(String)
  -    // Byte.valueOf(String,int radix)
  -    // Byte.valueOf(String)
  -    // Double.valueOf(String)
  -    // Float.valueOf(String)
  -    // new Float(String)
  -    // Integer.valueOf(String,int radix)
  -    // Integer.valueOf(String)
  -    // Integer.decode(String)
  -    // Integer.getInteger(String)
  -    // Integer.getInteger(String,int val)
  -    // Integer.getInteger(String,Integer val)
  -    // new Integer(String)
  -    // new Double(String)
  -    // new Byte(String)
  -    // new Long(String)
  -    // Long.getLong(String)
  -    // Long.getLong(String,int)
  -    // Long.getLong(String,Integer)
  -    // Long.valueOf(String,int)
  -    // Long.valueOf(String)
  -    // new Short(String)
  -    // Short.decode(String)
  -    // Short.valueOf(String,int)
  -    // Short.valueOf(String)
  -    // new BigDecimal(String)
  -    // new BigInteger(String)
  -    // new BigInteger(String,int radix)
  -    // Possible inputs:
  -    // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
  -    // plus minus everything. Prolly more. A lot are not separable.
  -
  -    /**
  -     * Turns a string value into a java.lang.Number.
  -     * Strategy is to look for a decimal point. If that is seen then
  -     * try first float and then try double.
  -     * If this fails, then try int and then long.
  -     * Assuming 50f fails and isn't 50, then try hexadecimal.
  -     *
  -     * @param val String containing a number
  -     *
  -     * @return Number created from the string
  -     */
  -    static public Number createNumber(String val) 
  -            throws NumberFormatException 
  -    {
  -        if (val == null) {
  -            return null;
  -        }
  -
  -        int idx = val.indexOf('.');                
  -        if ( (idx != -1) && (idx != val.length()-1) )  {
  -            try {
  -                return createFloat(val);
  -            } catch (NumberFormatException nfe) {
  -            }
  -            try {
  -                return createDouble(val);
  -            } catch (NumberFormatException nfe) {
  -            }
  -
  -            // look for all digits or '.' with f or F on end.
  -            if( val.endsWith("f") || val.endsWith("F") ) {
  -                String mant = val.substring(0,idx);
  -                String dec = val.substring(idx+1,val.length()-1);
  -                if(containsDigits(mant) && containsDigits(dec) ) {
  -                    try {
  -                        return createFloat(val.substring(0,val.length()-1));
  -                    } catch (NumberFormatException nfe) {
  -                    }
  -                }
  -            }
  -
  -            // look for all digits or '.' with d or D on end.
  -            if( val.endsWith("d") || val.endsWith("D") ) {
  -                String mant = val.substring(0,idx);
  -                String dec = val.substring(idx+1,val.length()-1);
  -                if(containsDigits(mant) && containsDigits(dec) ) {
  -                    try {
  -                        return createDouble(val.substring(0,val.length()-1));
  -                    } catch (NumberFormatException nfe) {
  -                    }
  -                }
  -            }
  -
  -            try {
  -                return createBigDecimal(val);
  -            } catch (NumberFormatException nfe) {
  -            }
  -
  -            throw new NumberFormatException("Unable to convert: "+val);
  -        }
  -
  -        try {
  -            return createInteger(val);
  -        } catch (NumberFormatException nfe) {
  -        }
  -        try {
  -            return createLong(val);
  -        } catch (NumberFormatException nfe) {
  -        }
  -
  -
  -        // look for all digits with l or L on the end.
  -        if( val.endsWith("l") || val.endsWith("L") ) {
  -            if(containsDigits(val.substring(0,val.length()-1))) {
  -                try {
  -                    return createLong(val.substring(0,val.length()-1));
  -                } catch (NumberFormatException nfe) {
  -                }
  -            }
  -        }
  -
  -
  -        try {
  -            return createBigInteger(val);
  -        } catch (NumberFormatException nfe) {
  -        }
  -
  -        // try Hex.
  -        try {
  -            return Integer.valueOf(val,16);
  -        } catch (NumberFormatException nfe) {
  -        }
  -
  -        throw new NumberFormatException("Unable to convert: "+val);
  -    }
  -
  -    /**
  -     * Return true if the string contains only digit characters.
  -     *
  -     * @param val String to check is only digits
  -     *
  -     * @return boolean contains only unicode numeric
  -     */
  -    static public boolean containsDigits(String val) {
  -        if(val == null) {
  -            return false; // ???
  -        }
  -        for(int i=0;i<val.length();i++) {
  -            if(!Character.isDigit(val.charAt(i))) {
  -                return false;
  -            }
  -        }
  -        return true;
  -    }
  -
  -    static public Float createFloat(String val) {
  -        return Float.valueOf(val);
  -    }
  -
  -    static public Double createDouble(String val) {
  -        return Double.valueOf(val);
  -    }
  -
  -    // handles 0xAABD and 0777 (hex and octal) as well.
  -    static public Integer createInteger(String val) {
  -        // return Integer.valueOf(val);
  -        return Integer.decode(val);
  -    }
  -
  -    static public Long createLong(String val) {
  -        return Long.valueOf(val);
  -    }
  -
  -    static public BigInteger createBigInteger(String val) {
  -        BigInteger bi = new BigInteger(val);
  -        return bi;
  -    }
  -
  -    static public BigDecimal createBigDecimal(String val) {
  -        BigDecimal bd = new BigDecimal(val);
  -        return bd;
  -    }
  -
  -    /**
  -     * Get the minimum of three values.
  -     */
  -    static public int minimum(int a, int b, int c) {
  -        if(b < a) {
  -            a = b;
  -        }
  -        if(c < a) {
  -            a = c;
  -        }
  -        return a;
  -    }
  -
  -    /**
  -     * Is a String a valid Java number.
  -     * Doesn't allow scientific notation.
  -     */
  -    static public boolean isNumber(String str) {
  -        char[] chrs = str.toCharArray();
  -        int sz = chrs.length;
  -        boolean decimal = false;
  -        for(int i=0; i<sz; i++) {
  -            // possibly faster as a continuous switch
  -            if( (chrs[i] >= '0') && (chrs[i] <= '9') ) {
  -                continue;
  -            }
  -            if(i==0) {
  -                if(chrs[i] == '-') {
  -                    continue;
  -                }
  -            }
  -            if(chrs[i] == '.') {
  -                if(!decimal) {
  -                    decimal = true;
  -                    continue;
  -                }
  -            }
  -            return false;
  -        }
  -        return true;
  -    }
  -
  -}
  +package org.apache.commons.lang;
  +
  +/* ====================================================================
  + * The Apache Software License, Version 1.1
  + *
  + * Copyright (c) 2001 The Apache Software Foundation.  All rights
  + * reserved.
  + *
  + * Redistribution and use in source and binary forms, with or without
  + * modification, are permitted provided that the following conditions
  + * are met:
  + *
  + * 1. Redistributions of source code must retain the above copyright
  + *    notice, this list of conditions and the following disclaimer.
  + *
  + * 2. Redistributions in binary form must reproduce the above copyright
  + *    notice, this list of conditions and the following disclaimer in
  + *    the documentation and/or other materials provided with the
  + *    distribution.
  + *
  + * 3. The end-user documentation included with the redistribution,
  + *    if any, must include the following acknowledgment:
  + *       "This product includes software developed by the
  + *        Apache Software Foundation (http://www.apache.org/)."
  + *    Alternately, this acknowledgment may appear in the software itself,
  + *    if and wherever such third-party acknowledgments normally appear.
  + *
  + * 4. The names "Apache" and "Apache Software Foundation" and
  + *    "Apache Commons" must not be used to endorse or promote products
  + *    derived from this software without prior written permission. For
  + *    written permission, please contact apache@apache.org.
  + *
  + * 5. Products derived from this software may not be called "Apache",
  + *    "Apache Turbine", nor may "Apache" appear in their name, without
  + *    prior written permission of the Apache Software Foundation.
  + *
  + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  + * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  + * SUCH DAMAGE.
  + * ====================================================================
  + *
  + * This software consists of voluntary contributions made by many
  + * individuals on behalf of the Apache Software Foundation.  For more
  + * information on the Apache Software Foundation, please see
  + * <http://www.apache.org/>.
  + */
  +
  +import java.math.BigInteger;
  +import java.math.BigDecimal;
  +/**
  + * Provides extra functionality for java Number classes.
  + *
  + * @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a>
  + * @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
  + * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
  + * @version $Id$
  + */
  +public final class Numbers {
  +
  +    /**
  +     * Convert a String to an int, returning zero if the conversion fails
  +     * 
  +     * @param str  the string to convert
  +     * @return the int represented by the string, or zero if conversion fails
  +     */
  +    public static int stringToInt(String str) {
  +        return stringToInt(str,0);
  +    }
  +    
  +    /**
  +     * Convert a String to an Int, returning a default value if the 
  +     * conversion fails.
  +     * 
  +     * @param str  the string to convert
  +     * @param defaultValue  the default value
  +     * @return the int represented by the string, or the default if conversion fails
  +     */
  +    public static int stringToInt(String str, int defaultValue) {
  +        try {
  +            return Integer.parseInt(str);
  +        } catch(NumberFormatException nfe) {
  +            return defaultValue;
  +        }
  +    }
  +
  +    // must handle Long, Float, Integer, Float, Short,
  +    //                  BigDecimal, BigInteger and Byte
  +    // useful methods:
  +    // Byte.decode(String)
  +    // Byte.valueOf(String,int radix)
  +    // Byte.valueOf(String)
  +    // Double.valueOf(String)
  +    // Float.valueOf(String)
  +    // new Float(String)
  +    // Integer.valueOf(String,int radix)
  +    // Integer.valueOf(String)
  +    // Integer.decode(String)
  +    // Integer.getInteger(String)
  +    // Integer.getInteger(String,int val)
  +    // Integer.getInteger(String,Integer val)
  +    // new Integer(String)
  +    // new Double(String)
  +    // new Byte(String)
  +    // new Long(String)
  +    // Long.getLong(String)
  +    // Long.getLong(String,int)
  +    // Long.getLong(String,Integer)
  +    // Long.valueOf(String,int)
  +    // Long.valueOf(String)
  +    // new Short(String)
  +    // Short.decode(String)
  +    // Short.valueOf(String,int)
  +    // Short.valueOf(String)
  +    // new BigDecimal(String)
  +    // new BigInteger(String)
  +    // new BigInteger(String,int radix)
  +    // Possible inputs:
  +    // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
  +    // plus minus everything. Prolly more. A lot are not separable.
  +
  +    /**
  +     * Turns a string value into a java.lang.Number.
  +     * Strategy is to look for a decimal point. If that is seen then
  +     * try first float and then try double.
  +     * If this fails, then try int and then long.
  +     * Assuming 50f fails and isn't 50, then try hexadecimal.
  +     *
  +     * @param val String containing a number
  +     * @return Number created from the string
  +     */
  +    public static Number createNumber(String val) 
  +            throws NumberFormatException {
  +        if (val == null) {
  +            return null;
  +        }
  +
  +        int idx = val.indexOf('.');                
  +        if ( (idx != -1) && (idx != val.length()-1) )  {
  +            try {
  +                return createFloat(val);
  +            } catch (NumberFormatException nfe) {
  +            }
  +            try {
  +                return createDouble(val);
  +            } catch (NumberFormatException nfe) {
  +            }
  +
  +            // look for all digits or '.' with f or F on end.
  +            if( val.endsWith("f") || val.endsWith("F") ) {
  +                String mant = val.substring(0,idx);
  +                String dec = val.substring(idx+1,val.length()-1);
  +                if(containsDigits(mant) && containsDigits(dec) ) {
  +                    try {
  +                        return createFloat(val.substring(0,val.length()-1));
  +                    } catch (NumberFormatException nfe) {
  +                    }
  +                }
  +            }
  +
  +            // look for all digits or '.' with d or D on end.
  +            if( val.endsWith("d") || val.endsWith("D") ) {
  +                String mant = val.substring(0,idx);
  +                String dec = val.substring(idx+1,val.length()-1);
  +                if(containsDigits(mant) && containsDigits(dec) ) {
  +                    try {
  +                        return createDouble(val.substring(0,val.length()-1));
  +                    } catch (NumberFormatException nfe) {
  +                    }
  +                }
  +            }
  +
  +            try {
  +                return createBigDecimal(val);
  +            } catch (NumberFormatException nfe) {
  +            }
  +
  +            throw new NumberFormatException("Unable to convert: "+val);
  +        }
  +
  +        try {
  +            return createInteger(val);
  +        } catch (NumberFormatException nfe) {
  +        }
  +        try {
  +            return createLong(val);
  +        } catch (NumberFormatException nfe) {
  +        }
  +
  +
  +        // look for all digits with l or L on the end.
  +        if( val.endsWith("l") || val.endsWith("L") ) {
  +            if(containsDigits(val.substring(0,val.length()-1))) {
  +                try {
  +                    return createLong(val.substring(0,val.length()-1));
  +                } catch (NumberFormatException nfe) {
  +                }
  +            }
  +        }
  +
  +
  +        try {
  +            return createBigInteger(val);
  +        } catch (NumberFormatException nfe) {
  +        }
  +
  +        // try Hex.
  +        try {
  +            return Integer.valueOf(val,16);
  +        } catch (NumberFormatException nfe) {
  +        }
  +
  +        throw new NumberFormatException("Unable to convert: "+val);
  +    }
  +
  +    /**
  +     * Convert a String to a Float
  +     * 
  +     * @param val  a String to convert
  +     * @return converted Float
  +     */
  +    public static Float createFloat(String val) {
  +        return Float.valueOf(val);
  +    }
  +
  +    /**
  +     * Convert a String to a Double
  +     * 
  +     * @param val  a String to convert
  +     * @return converted Double
  +     */
  +    public static Double createDouble(String val) {
  +        return Double.valueOf(val);
  +    }
  +
  +    /**
  +     * Convert a String to a Integer, handling hex and
  +     * octal notations.
  +     * 
  +     * @param val  a String to convert
  +     * @return converted Integer
  +     */
  +    public static Integer createInteger(String val) {
  +        // decode() handles 0xAABD and 0777 (hex and octal) as well.
  +        return Integer.decode(val);
  +    }
  +
  +    /**
  +     * Convert a String to a Long
  +     * 
  +     * @param val  a String to convert
  +     * @return converted Long
  +     */
  +    public static Long createLong(String val) {
  +        return Long.valueOf(val);
  +    }
  +
  +    /**
  +     * Convert a String to a BigInteger
  +     * 
  +     * @param val  a String to convert
  +     * @return converted BigInteger
  +     */
  +    public static BigInteger createBigInteger(String val) {
  +        BigInteger bi = new BigInteger(val);
  +        return bi;
  +    }
  +
  +    /**
  +     * Convert a String to a BigDecimal
  +     * 
  +     * @param val  a String to convert
  +     * @return converted BigDecimal
  +     */
  +    public static BigDecimal createBigDecimal(String val) {
  +        BigDecimal bd = new BigDecimal(val);
  +        return bd;
  +    }
  +
  +    /**
  +     * Get the minimum of three values.
  +     */
  +    public static int minimum(int a, int b, int c) {
  +        if (b < a) {
  +            a = b;
  +        }
  +        if (c < a) {
  +            a = c;
  +        }
  +        return a;
  +    }
  +
  +    /**
  +     * Get the maximum of three values.
  +     */
  +    public static int maximum(int a, int b, int c) {
  +        if (b > a) {
  +            a = b;
  +        }
  +        if (c > a) {
  +            a = c;
  +        }
  +        return a;
  +    }
  +
  +    /**
  +     * Return true if the string contains only digit characters.
  +     * Null and blank string will return false.
  +     *
  +     * @param val  String to check is only digits
  +     * @return boolean contains only unicode numeric
  +     */
  +    public static boolean containsDigits(String val) {
  +        if (val == null) {
  +            return false;
  +        }
  +        for (int i=0;i<val.length();i++) {
  +            if (!Character.isDigit(val.charAt(i))) {
  +                return false;
  +            }
  +        }
  +        return (val.length() > 0);
  +    }
  +
  +    /**
  +     * Is a String a valid Java number. [-][0-9][.][0-9].
  +     * Doesn't allow scientific notation.
  +     * 
  +     * @param str  the string to check
  +     * @return true if the string is a correctly formatted number
  +     */
  +    public static boolean isNumber(String str) {
  +        char[] chrs = str.toCharArray();
  +        int sz = chrs.length;
  +        boolean decimal = false;
  +        for (int i=0; i<sz; i++) {
  +            // possibly faster as a continuous switch
  +            if( (chrs[i] >= '0') && (chrs[i] <= '9') ) {
  +                continue;
  +            }
  +            if (i==0) {
  +                if (chrs[i] == '-') {
  +                    continue;
  +                }
  +            }
  +            if (chrs[i] == '.') {
  +                if(!decimal) {
  +                    decimal = true;
  +                    continue;
  +                }
  +            }
  +            return false;
  +        }
  +        return true;
  +    }
  +
  +}
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message