01: /*
02: * Copyright 2003-2004 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.apache.commons.math.util;
18:
19: import java.io.Serializable;
20:
21: import org.apache.commons.math.MathException;
22:
23: /**
24: * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This
25: * provides some simple conversion capabilities to turn any java/lang.Number
26: * into a primitive double or to turn a String representation of a Number into
27: * a double.
28: *
29: * @version $Revision: 348519 $ $Date: 2005-11-23 12:12:18 -0700 (Wed, 23 Nov 2005) $
30: */
31: public class DefaultTransformer implements NumberTransformer,
32: Serializable {
33:
34: /** Serializable version identifier */
35: private static final long serialVersionUID = 4019938025047800455L;
36:
37: /**
38: * @param o the object that gets transformed.
39: * @return a double primitive representation of the Object o.
40: * @throws org.apache.commons.math.MathException If it cannot successfully
41: * be transformed or is null.
42: * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
43: */
44: public double transform(Object o) throws MathException {
45:
46: if (o == null) {
47: throw new MathException(
48: "Conversion Exception in Transformation, Object is null");
49: }
50:
51: if (o instanceof Number) {
52: return ((Number) o).doubleValue();
53: }
54:
55: try {
56: return new Double(o.toString()).doubleValue();
57: } catch (Exception e) {
58: throw new MathException(
59: "Conversion Exception in Transformation: "
60: + e.getMessage(), e);
61: }
62: }
63: }
|