1 | package ise.antelope.tasks.util.math;
|
---|
2 |
|
---|
3 |
|
---|
4 | /**
|
---|
5 | * Represents a number.
|
---|
6 | * <p>Copyright 2003, Dale Anson, all rights reserved
|
---|
7 | * @author Dale Anson, [email protected]
|
---|
8 | */
|
---|
9 | public class Num {
|
---|
10 |
|
---|
11 | // the value of this number
|
---|
12 | private String value = null;
|
---|
13 |
|
---|
14 | private String datatype = null;
|
---|
15 |
|
---|
16 | public Num() {
|
---|
17 | }
|
---|
18 |
|
---|
19 | public Num( String value ) {
|
---|
20 | setValue( value );
|
---|
21 | }
|
---|
22 |
|
---|
23 | /**
|
---|
24 | * Set the value for this number. This string must parse to the set
|
---|
25 | * datatype, for example, setting value to "7.992" and datatype to INT
|
---|
26 | * will cause a number format exception to be thrown. Supports two special
|
---|
27 | * numbers, "E" and "PI".
|
---|
28 | * @param value the value for this number
|
---|
29 | */
|
---|
30 | public void setValue( String value ) {
|
---|
31 | if ( value.equals( "E" ) )
|
---|
32 | value = String.valueOf( java.lang.Math.E );
|
---|
33 | else if ( value.equals( "PI" ) )
|
---|
34 | value = String.valueOf( java.lang.Math.PI );
|
---|
35 | this.value = value;
|
---|
36 | }
|
---|
37 |
|
---|
38 | /**
|
---|
39 | * @return the value for this number as a Number. Cast as appropriate to
|
---|
40 | * Integer, Long, Float, or Double.
|
---|
41 | */
|
---|
42 | public Number getValue() {
|
---|
43 | try {
|
---|
44 | if ( datatype == null )
|
---|
45 | datatype = "double";
|
---|
46 | if ( datatype.equals( "int" ) )
|
---|
47 | return new Integer( value );
|
---|
48 | if ( datatype.equals( "long" ) )
|
---|
49 | return new Long( value );
|
---|
50 | if ( datatype.equals( "float" ) )
|
---|
51 | return new Float( value );
|
---|
52 | if ( datatype.equals( "double" ) )
|
---|
53 | return new Double( value );
|
---|
54 | if ( datatype.equals( "bigint" ) )
|
---|
55 | return new java.math.BigInteger( value );
|
---|
56 | if ( datatype.equals( "bigdecimal" ) )
|
---|
57 | return new java.math.BigDecimal( value );
|
---|
58 | throw new RuntimeException( "Invalid datatype." );
|
---|
59 | }
|
---|
60 | catch ( NumberFormatException nfe ) {
|
---|
61 | return new Double( value );
|
---|
62 | }
|
---|
63 | }
|
---|
64 |
|
---|
65 | /**
|
---|
66 | * Sets the datatype of this number. Allowed values are
|
---|
67 | * "int", "long", "float", or "double".
|
---|
68 | */
|
---|
69 | public void setDatatype( String p ) {
|
---|
70 | datatype = p;
|
---|
71 | }
|
---|
72 |
|
---|
73 | /**
|
---|
74 | * @return the datatype as one of the defined types.
|
---|
75 | */
|
---|
76 | public String getDatatype() {
|
---|
77 | if ( datatype == null )
|
---|
78 | datatype = "double";
|
---|
79 | return datatype;
|
---|
80 | }
|
---|
81 |
|
---|
82 | public String toString() {
|
---|
83 | if (value == null)
|
---|
84 | return null;
|
---|
85 | return getValue().toString();
|
---|
86 | }
|
---|
87 | }
|
---|
88 |
|
---|