View Javadoc

1   /*
2    * #%L
3    * prolobjectlink-jpi-jtrolog
4    * %%
5    * Copyright (C) 2012 - 2018 WorkLogic Project
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU Lesser General Public License as
9    * published by the Free Software Foundation, either version 2.1 of the
10   * License, or (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Lesser Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Lesser Public
18   * License along with this program.  If not, see
19   * <http://www.gnu.org/licenses/lgpl-2.1.html>.
20   * #L%
21   */
22  package jTrolog.terms;
23  
24  /**
25   * Number abstract class represents numbers prolog data type
26   */
27  @SuppressWarnings({ "serial" })
28  public abstract class Number extends EvaluableTerm {
29  
30  	protected Number() {
31  		type = Term.NUMBER;
32  	}
33  
34  	// two real numbers that are similiar within this margin are considered
35  	// equal
36  	public static final double MARGIN = 0.0000000000000005;
37  
38  	/**
39  	 * Returns the value of the number as int
40  	 */
41  	public abstract int intValue();
42  
43  	/**
44  	 * Returns the value of the number as float
45  	 */
46  	public abstract float floatValue();
47  
48  	/**
49  	 * Returns the value of the number as long
50  	 */
51  	public abstract long longValue();
52  
53  	/**
54  	 * Returns the value of the number as double
55  	 */
56  	public abstract double doubleValue();
57  
58  	/**
59  	 * @return 0 if one is the same as two (within the MARGIN of error) 1 if one
60  	 *         is greater than two -1 if one is smaller than two
61  	 */
62  	public static int compareDoubleValues(Number one, Number two) {
63  		double value = one.doubleValue() - two.doubleValue();
64  		if (value > 0 ? value < MARGIN : -value < MARGIN)
65  			return 0;
66  		return value > 0 ? 1 : -1;
67  	}
68  
69  	public static Number create(String s) throws NumberFormatException {
70  		try {
71  			return Int.create(s);
72  		} catch (NumberFormatException ee) {
73  			return new Double(s);
74  		}
75  	}
76  
77  	public static Number getIntegerNumber(long num) {
78  		if (num > Integer.MIN_VALUE && num < Integer.MAX_VALUE)
79  			return new Int((int) num);
80  		return new Long(num);
81  	}
82  
83  	public String toStringSmall() {
84  		return toString();
85  	}
86  }