001 package railo.runtime.functions.string; 002 003 import railo.commons.lang.StringUtil; 004 import railo.runtime.PageContext; 005 import railo.runtime.exp.ExpressionException; 006 import railo.runtime.exp.PageException; 007 008 public class ParseNumber { 009 private static final int BIN=2; 010 private static final int OCT=8; 011 private static final int DEC=10; 012 private static final int HEX=16; 013 014 public static double call(PageContext pc , String strNumber) throws PageException { 015 return call(pc,strNumber,null); 016 } 017 018 public static double call(PageContext pc , String strNumber,String strRadix) throws PageException { 019 return invoke(strNumber, strRadix); 020 } 021 022 public static double invoke(String strNumber,String strRadix, double defaultValue) { 023 try { 024 return invoke(strNumber, strRadix); 025 } catch (PageException e) { 026 return defaultValue; 027 } 028 } 029 public static double invoke(String strNumber,String strRadix) throws PageException { 030 strNumber=strNumber.trim(); 031 int radix=DEC; 032 if(strRadix==null) { 033 if(StringUtil.startsWithIgnoreCase(strNumber, "0x")){ 034 radix=HEX; 035 strNumber=strNumber.substring(2); 036 } 037 else if(strNumber.startsWith("#")){ 038 radix=HEX; 039 strNumber=strNumber.substring(1); 040 } 041 else if(strNumber.startsWith("0") && strNumber.length()>1){ 042 radix=OCT; 043 strNumber=strNumber.substring(1); 044 } 045 } 046 else { 047 strRadix=strRadix.trim().toLowerCase(); 048 049 if(strRadix.startsWith("bin"))radix=BIN; 050 else if(strRadix.startsWith("oct"))radix=OCT; 051 else if(strRadix.startsWith("dec"))radix=DEC; 052 else if(strRadix.startsWith("hex")){ 053 if(StringUtil.startsWithIgnoreCase(strNumber, "0x")) strNumber=strNumber.substring(2); 054 else if(strNumber.startsWith("#")) strNumber=strNumber.substring(1); 055 056 radix=HEX; 057 } 058 else throw new ExpressionException("invalid radix defintions, valid vales are [bin,oct,dec,hex]"); 059 060 } 061 062 if(radix==OCT && strNumber.indexOf('9')!=-1) 063 throw new ExpressionException("digit [9] is out of range for a octal number"); 064 065 066 if(strNumber.indexOf('.')!=-1){ 067 if(radix!=DEC) 068 throw new ExpressionException("the radix con only be [dec] for floating point numbers"); 069 return Double.parseDouble(strNumber); 070 } 071 return Integer.parseInt(strNumber,radix); 072 } 073 074 }