001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019/**
020 * Implements the CFML Function val
021 */
022package lucee.runtime.functions.string;
023
024import lucee.runtime.PageContext;
025import lucee.runtime.exp.PageException;
026import lucee.runtime.ext.function.Function;
027import lucee.runtime.op.Caster;
028import lucee.runtime.op.Decision;
029
030public final class Val implements Function {
031        
032        private static final long serialVersionUID = 6319751040478371142L;
033
034        public static double call(PageContext pc , String value) throws PageException {
035            if(value==null) return 0;
036            value=value.trim();
037            int pos=getPos(value);
038            if(pos<=0)return 0;
039                return Caster.toDoubleValue(value.substring(0,pos));
040        }
041        
042        private static int getPos(String str) { 
043        if(str==null) return 0; 
044        
045        int pos=0; 
046        int len=str.length(); 
047        if(len==0) return 0; 
048        char curr=str.charAt(pos); 
049        
050        if(curr=='+' || curr=='-') { 
051                if(len==++pos) return 0; 
052                curr=str.charAt(pos); 
053        }
054        
055        // at least one digit 
056        if(curr>='0' && curr<='9') { 
057                curr=str.charAt(pos); 
058        }
059        else if(curr=='.'){
060                curr='.';
061        }
062        else return 0; 
063
064        boolean hasDot=false; 
065        //boolean hasExp=false; 
066        for(;pos<len;pos++) { 
067            curr=str.charAt(pos); 
068            if(curr<'0') {
069                if(curr=='.') { 
070                    if(pos+1>=len || hasDot) return pos; 
071                    hasDot=true; 
072                } 
073                else return pos;
074            }
075            else if(curr>'9') {
076                /*if(curr=='e' || curr=='E') { 
077                    if(pos+1>=len || hasExp) return pos; 
078                    hasExp=true; 
079                    hasDot=true; 
080                }
081                else */
082                        return pos;
083            }
084        } 
085        
086        return pos; 
087    } 
088}