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 **/
019package lucee.runtime.functions.other;
020
021import lucee.runtime.PageContext;
022import lucee.runtime.exp.FunctionException;
023import lucee.runtime.exp.PageException;
024import lucee.runtime.op.Caster;
025import lucee.runtime.op.Decision;
026
027public class ToNumeric {
028        public static double call(PageContext pc , Object value) throws PageException {
029                return Caster.toDoubleValue(value);
030        }
031        public static double call(PageContext pc , Object value, Object oRadix) throws PageException {
032                if(oRadix==null) return call(pc, value);
033                int radix;
034                if(Decision.isNumeric(oRadix)){
035                        radix=Caster.toIntValue(oRadix);
036                        if(radix<Character.MIN_RADIX || radix>Character.MAX_RADIX)
037                                throw invalidRadix(pc, Caster.toString(radix));
038                }
039                else {
040                        String str = Caster.toString(oRadix).trim().toLowerCase();
041                        if("bin".equals(str)) radix=2;
042                        else if("oct".equals(str)) radix=8;
043                        else if("dec".equals(str)) radix=10;
044                        else if("hex".equals(str)) radix=16;
045                        else throw invalidRadix(pc,str);
046                }
047                
048                return Integer.parseInt(Caster.toString(value), radix);
049        }
050        
051        private static FunctionException invalidRadix(PageContext pc , String radix) {
052                return new FunctionException(pc, "ToNumeric", 2, "radix", "invalid value ["+radix+"], valid values are ["+Character.MIN_RADIX+"-"+Character.MAX_RADIX+",bin,oct,dec,hex]");
053        }
054}