01: // Modified or written by Object Mentor, Inc. for inclusion with FitNesse.
02: // Copyright (c) 2002 Cunningham & Cunningham, Inc.
03: // Released under the terms of the GNU General Public License version 2 or later.
04: package fit;
05:
06: // Copyright (c) 2002 Cunningham & Cunningham, Inc.
07: // Released under the terms of the GNU General Public License version 2 or later.
08:
09: // Warning: not (yet) a general number usable in all calculations.
10:
11: public class ScientificDouble extends Number implements Comparable {
12: protected double value;
13: protected double precision;
14:
15: public ScientificDouble(double value) {
16: this .value = value;
17: this .precision = 0;
18: }
19:
20: public static ScientificDouble valueOf(String s) {
21: ScientificDouble result = new ScientificDouble(Double
22: .parseDouble(s));
23: result.precision = precision(s);
24: return result;
25: }
26:
27: public static ScientificDouble parse(String s) {
28: return valueOf(s);
29: }
30:
31: public static double precision(String s) {
32: double value = Double.parseDouble(s);
33: double bound = Double.parseDouble(tweak(s.trim()));
34: return Math.abs(bound - value);
35: }
36:
37: public static String tweak(String s) {
38: int pos;
39: if ((pos = s.toLowerCase().indexOf("e")) >= 0) {
40: return tweak(s.substring(0, pos)) + s.substring(pos);
41: }
42: if (s.indexOf(".") >= 0) {
43: return s + "5";
44: }
45: return s + ".5";
46: }
47:
48: public boolean equals(Object obj) {
49: return compareTo(obj) == 0;
50: }
51:
52: public int compareTo(Object obj) {
53: double other = ((Number) obj).doubleValue();
54: double diff = value - other;
55: // System.out.println(value+" "+precision+" "+diff);
56: if (diff < -precision)
57: return -1;
58: if (diff > precision)
59: return 1;
60: if (Double.isNaN(value) && Double.isNaN(other))
61: return 0;
62: if (Double.isNaN(value))
63: return 1;
64: if (Double.isNaN(other))
65: return -1;
66: return 0;
67: }
68:
69: public String toString() {
70: return Double.toString(value);
71: }
72:
73: public double doubleValue() {
74: return value;
75: }
76:
77: public float floatValue() {
78: return (float) value;
79: }
80:
81: public long longValue() {
82: return (long) value;
83: }
84:
85: public int intValue() {
86: return (int) value;
87: }
88: }
|