KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > appfuse > util > CurrencyConverter


1 package org.appfuse.util;
2
3 import java.text.DecimalFormat JavaDoc;
4 import java.text.ParseException JavaDoc;
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 /**
13  * This class is converts a Double to a double-digit String
14  * (and vise-versa) by BeanUtils when copying properties.
15  * Registered for use in BaseAction.
16  *
17  * <p>
18  * <a HREF="CurrencyConverter.java.htm"><i>View Source</i></a>
19  * </p>
20  *
21  * @author <a HREF="mailto:matt@raibledesigns.com">Matt Raible</a>
22  */

23 public class CurrencyConverter implements Converter {
24     protected final Log log = LogFactory.getLog(CurrencyConverter.class);
25     protected final DecimalFormat JavaDoc formatter = new DecimalFormat JavaDoc("###,###.00");
26
27     /**
28      * Convert a String to a Double and a Double to a String
29      *
30      * @param type the class type to output
31      * @param value the object to convert
32      * @return object the converted object (Double or String)
33      */

34     public final Object JavaDoc convert(final Class JavaDoc type, final Object JavaDoc value) {
35         // for a null value, return null
36
if (value == null) {
37             return null;
38         } else {
39             if (value instanceof String JavaDoc) {
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                     //formatter.setDecimalSeparatorAlwaysShown(true);
54
Number JavaDoc num = formatter.parse(String.valueOf(value));
55
56                     return new Double JavaDoc(num.doubleValue());
57                 } catch (ParseException JavaDoc pe) {
58                     pe.printStackTrace();
59                 }
60             } else if (value instanceof Double JavaDoc) {
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