1 package org.appfuse.util; 2 3 import java.text.DecimalFormat ; 4 import java.text.ParseException ; 5 6 import org.apache.commons.beanutils.ConversionException; 7 import org.apache.commons.beanutils.Converter; 8 import org.apache.commons.lang.StringUtils; 9 import org.apache.commons.logging.Log; 10 import org.apache.commons.logging.LogFactory; 11 12 23 public class CurrencyConverter implements Converter { 24 protected final Log log = LogFactory.getLog(CurrencyConverter.class); 25 protected final DecimalFormat formatter = new DecimalFormat ("###,###.00"); 26 27 34 public final Object convert(final Class type, final Object value) { 35 if (value == null) { 37 return null; 38 } else { 39 if (value instanceof String ) { 40 if (log.isDebugEnabled()) { 41 log.debug("value (" + value + ") instance of String"); 42 } 43 44 try { 45 if (StringUtils.isBlank(String.valueOf(value))) { 46 return null; 47 } 48 49 if (log.isDebugEnabled()) { 50 log.debug("converting '" + value + "' to a decimal"); 51 } 52 53 Number num = formatter.parse(String.valueOf(value)); 55 56 return new Double (num.doubleValue()); 57 } catch (ParseException pe) { 58 pe.printStackTrace(); 59 } 60 } else if (value instanceof Double ) { 61 if (log.isDebugEnabled()) { 62 log.debug("value (" + value + ") instance of Double"); 63 log.debug("returning double: " + formatter.format(value)); 64 } 65 66 return formatter.format(value); 67 } 68 } 69 70 throw new ConversionException("Could not convert " + value + " to " + 71 type.getName() + "!"); 72 } 73 } 74 | Popular Tags |