Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Help with java method please

    I'm trying to return a true statement if the string represents a double. Here is what I compiled, please let me know if this is right.

    Code:
    	public static boolean isDouble(String source) {
    		if (source == null) {
    			return false;
    		}
    		int length = source.length();
    		else if (length	== 0) {
    			return false;
    		}
    		int i = 0; 
    		else if (source.charAt(0) == '-') {
    				if (length == 1) {
    						return false;
    				}
    				i = 1;
    		}
    		for (; i < length; i++) {
    				char c = source.charAt(i);
    				if  (c < '0' || c > '9') {
    						return false;
    				}
    		}
    		else return true;
    		
    	} //End isDouble

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Double also allows scientific notation within it, where a negative can be placed beyond the first character (ie: -4.225e-5 is valid). Otherwise, you are on the right track, but you need to account for the +/- signs (which may show up at either the first character or immediately proceeding a 'e'), a single 'e', numbers 0-9, and a single decimal point.
    Rather than just writing rules for this, its much faster to simply try to parse it instead.
    PHP Code:
        public static boolean isDouble(String s)
        {
            
    boolean bResult false;
            try
            {
                
    Double.parseDouble(s); // Can toss NumberFormatException or NullPointerException
                
    bResult true;
            }
            catch (
    Exception ex)
            {
            }
            
            return 
    bResult;
        } 
    Alternatively, pattern matching may provide an overall easier solution than breaking it up char by char and comparing what it is to what is usable ('e' and '.' must occur only once).
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •