1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 abstract class JSNumber extends JSPrimitive {
8 boolean jsequals(JS o) {
9 if(o == this) return true;
10 if(o instanceof JSNumber) {
11 JSNumber n = (JSNumber) o;
12 if(this instanceof D || n instanceof D) return n.toDouble() == toDouble();
13 return n.toLong() == toLong();
14 } else if(o instanceof JSString) {
15 String s = ((JSString)o).s.trim();
17 if(this instanceof D || s.indexOf('.') != -1) return Double.parseDouble(s) == toDouble();
18 return Long.parseLong(s) == toLong();
19 } catch(NumberFormatException e) {
26 // FEATURE: Better hash function? (if d != (int) d then do something double specific)
27 public int hashCode() { return toInt(); }
30 long toLong() { return toInt(); }
31 boolean toBoolean() { return toInt() != 0; }
32 double toDouble() { return toLong(); }
33 float toFloat() { return (float) toDouble(); }
35 final static class I extends JSNumber {
37 I(int i) { this.i = i; }
38 int toInt() { return i; }
39 public String coerceToString() { return Integer.toString(i); }
42 final static class L extends JSNumber {
44 L(long l) { this.l = l; }
45 int toInt() { return (int) l; }
46 long toLong() { return l; }
47 public String coerceToString() { return Long.toString(l); }
50 final static class D extends JSNumber {
51 private final double d;
52 D(double d) { this.d = d; }
53 int toInt() { return (int) d; }
54 long toLong() { return (long) d; }
55 double toDouble() { return d; }
56 boolean toBoolean() { return d == d && d != 0.0; }
57 public String coerceToString() { return d == (long) d ? Long.toString((long)d) : Double.toString(d); }
60 final static class B extends JSNumber {
61 private final boolean b;
62 B(boolean b) { this.b = b; }
63 int toInt() { return b ? 1 : 0; }
64 public String coerceToString() { return b ? "true" : "false"; }