1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.math.util;
19
20 import java.io.Serializable;
21
22 import org.apache.commons.math.MathException;
23
24 /**
25 * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This
26 * provides some simple conversion capabilities to turn any java/lang.Number
27 * into a primitive double or to turn a String representation of a Number into
28 * a double.
29 *
30 * @version $Revision: 506600 $ $Date: 2007-02-12 12:35:59 -0700 (Mon, 12 Feb 2007) $
31 */
32 public class DefaultTransformer implements NumberTransformer, 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("Conversion Exception in Transformation, Object is null", new Object[0]);
48 }
49
50 if (o instanceof Number) {
51 return ((Number)o).doubleValue();
52 }
53
54 try {
55 return new Double(o.toString()).doubleValue();
56 } catch (Exception e) {
57 throw new MathException("Conversion Exception in Transformation: {0}",
58 new Object[] { e.getMessage() }, e);
59 }
60 }
61 }