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