001    /**
002     * Implements the Cold Fusion Function val
003     */
004    package railo.runtime.functions.string;
005    
006    import railo.runtime.PageContext;
007    import railo.runtime.exp.PageException;
008    import railo.runtime.ext.function.Function;
009    import railo.runtime.op.Caster;
010    import railo.runtime.op.Decision;
011    
012    public final class Val implements Function {
013            
014            public static double call(PageContext pc , Object value) throws PageException {
015                String str=Caster.toString(value);
016            str=str.trim();
017                int pos=getPos(str);
018                if(pos<=0) {
019                        if(Decision.isBoolean(str)) return Caster.toDoubleValue(str);
020                        return 0;
021                    }
022                    return Caster.toDoubleValue(str.substring(0,pos));
023            }
024            
025            private static int getPos(String str) { 
026            if(str==null) return 0; 
027            
028            int pos=0; 
029            int len=str.length(); 
030            if(len==0) return 0; 
031            char curr=str.charAt(pos); 
032            
033            if(curr=='+' || curr=='-') { 
034                    if(len==++pos) return 0; 
035                    curr=str.charAt(pos); 
036            }
037            
038            // at least one digit 
039            if(curr>='0' && curr<='9') { 
040                    curr=str.charAt(pos); 
041            }
042            else if(curr=='.'){
043                    curr='.';
044            }
045            else return 0; 
046    
047            boolean hasDot=false; 
048            boolean hasExp=false; 
049            for(;pos<len;pos++) { 
050                curr=str.charAt(pos); 
051                if(curr<'0') {
052                    if(curr=='.') { 
053                        if(pos+1>=len || hasDot) return pos; 
054                        hasDot=true; 
055                    } 
056                    else return pos;
057                }
058                else if(curr>'9') {
059                    /*if(curr=='e' || curr=='E') { 
060                        if(pos+1>=len || hasExp) return pos; 
061                        hasExp=true; 
062                        hasDot=true; 
063                    }
064                    else */
065                            return pos;
066                }
067            } 
068            
069            return pos; 
070        } 
071    }