KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > format > NumberHandler


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.format;
14
15 import java.text.DecimalFormat JavaDoc;
16 import java.text.ParsePosition JavaDoc;
17
18
19 /**
20  * parses/prints numbers via DecimalFormat
21  */

22 public abstract class NumberHandler extends FormatHandlerSupport {
23   double minValue = Double.NaN;
24   
25   public String JavaDoc format(Object JavaDoc o, String JavaDoc userPattern) {
26     if (o == null) {
27       return "";
28     }
29
30     DecimalFormat JavaDoc df = (DecimalFormat JavaDoc) DecimalFormat.getNumberInstance(getLocale());
31     df.applyPattern(findPattern(userPattern));
32
33     return df.format(o);
34   }
35
36
37   public Object JavaDoc parse(String JavaDoc s, String JavaDoc userPattern) throws FormatException {
38     if (s == null) {
39       throw new FormatException(getErrorMessage(""));
40     }
41
42     s = s.trim();
43
44     if (s.length() == 0) {
45       throw new FormatException(getErrorMessage(""));
46     }
47
48     DecimalFormat JavaDoc df = (DecimalFormat JavaDoc) DecimalFormat.getNumberInstance(getLocale());
49     df.applyPattern(findPattern(userPattern));
50
51     ParsePosition JavaDoc pos = new ParsePosition JavaDoc(0);
52     Number JavaDoc n = (Number JavaDoc) df.parse(s, pos);
53
54     if ((n == null) || (pos.getIndex() != s.length()))
55       throw new FormatException(getErrorMessage(s));
56     
57     if (!Double.isNaN(minValue) && n.doubleValue() < minValue)
58       throw new FormatException(getErrorMessage(s));
59
60     return n;
61   }
62
63   /**
64    * Returns the minValue.
65    * @return double
66    */

67   public double getMinValue() {
68     return minValue;
69   }
70
71   /**
72    * Sets the minValue.
73    * @param minValue The minValue to set
74    */

75   public void setMinValue(double minValue) {
76     this.minValue = minValue;
77   }
78
79 }
Popular Tags