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 java.lang;
19 
20 /**
21  * The wrapper for the primitive type {@code double}.
22  *
23  * @see java.lang.Number
24  * @since 1.0
25  */
26 public final class Double extends Number implements Comparable<Double> {
27     static final int EXPONENT_BIAS = 1023;
28 
29     static final int EXPONENT_BITS = 12;
30     static final int MANTISSA_BITS = 52;
31     static final int NON_MANTISSA_BITS = 12;
32 
33     static final long SIGN_MASK     = 0x8000000000000000L;
34     static final long EXPONENT_MASK = 0x7ff0000000000000L;
35     static final long MANTISSA_MASK = 0x000fffffffffffffL;
36 
37     private static final long serialVersionUID = -9172774392245257468L;
38 
39     /**
40      * The value which the receiver represents.
41      */
42     private final double value;
43 
44     /**
45      * Constant for the maximum {@code double} value, (2 - 2<sup>-52</sup>) *
46      * 2<sup>1023</sup>.
47      */
48     public static final double MAX_VALUE = 1.79769313486231570e+308;
49 
50     /**
51      * Constant for the minimum {@code double} value, 2<sup>-1074</sup>.
52      */
53     public static final double MIN_VALUE = 5e-324;
54 
55     /* 4.94065645841246544e-324 gets rounded to 9.88131e-324 */
56 
57     /**
58      * Constant for the Not-a-Number (NaN) value of the {@code double} type.
59      */
60     public static final double NaN = 0.0 / 0.0;
61 
62     /**
63      * Constant for the positive infinity value of the {@code double} type.
64      */
65     public static final double POSITIVE_INFINITY = 1.0 / 0.0;
66 
67     /**
68      * Constant for the negative infinity value of the {@code double} type.
69      */
70     public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
71 
72     /**
73      * Constant for the smallest positive normal value of the {@code double} type.
74      *
75      * @since 1.6
76      */
77     public static final double MIN_NORMAL = 2.2250738585072014E-308;
78 
79     /**
80      * Maximum base-2 exponent that a finite value of the {@code double} type may have.
81      * Equal to {@code Math.getExponent(Double.MAX_VALUE)}.
82      *
83      * @since 1.6
84      */
85     public static final int MAX_EXPONENT = 1023;
86 
87     /**
88      * Minimum base-2 exponent that a normal value of the {@code double} type may have.
89      * Equal to {@code Math.getExponent(Double.MIN_NORMAL)}.
90      *
91      * @since 1.6
92      */
93     public static final int MIN_EXPONENT = -1022;
94 
95     /**
96      * The {@link Class} object that represents the primitive type {@code
97      * double}.
98      *
99      * @since 1.1
100      */
101     @SuppressWarnings("unchecked")
102     public static final Class<Double> TYPE
103             = (Class<Double>) double[].class.getComponentType();
104     // Note: Double.TYPE can't be set to "double.class", since *that* is
105     // defined to be "java.lang.Double.TYPE";
106 
107     /**
108      * Constant for the number of bits needed to represent a {@code double} in
109      * two's complement form.
110      *
111      * @since 1.5
112      */
113     public static final int SIZE = 64;
114 
115     /**
116      * Constructs a new {@code Double} with the specified primitive double
117      * value.
118      *
119      * @param value
120      *            the primitive double value to store in the new instance.
121      */
Double(double value)122     public Double(double value) {
123         this.value = value;
124     }
125 
126     /**
127      * Constructs a new {@code Double} from the specified string.
128      *
129      * @param string
130      *            the string representation of a double value.
131      * @throws NumberFormatException
132      *             if {@code string} cannot be parsed as a double value.
133      * @see #parseDouble(String)
134      */
Double(String string)135     public Double(String string) throws NumberFormatException {
136         this(parseDouble(string));
137     }
138 
139     /**
140      * Compares this object to the specified double object to determine their
141      * relative order. There are two special cases:
142      * <ul>
143      * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
144      * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
145      * <li>+0.0d is greater than -0.0d</li>
146      * </ul>
147      *
148      * @param object
149      *            the double object to compare this object to.
150      * @return a negative value if the value of this double is less than the
151      *         value of {@code object}; 0 if the value of this double and the
152      *         value of {@code object} are equal; a positive value if the value
153      *         of this double is greater than the value of {@code object}.
154      * @throws NullPointerException
155      *             if {@code object} is {@code null}.
156      * @see java.lang.Comparable
157      * @since 1.2
158      */
compareTo(Double object)159     public int compareTo(Double object) {
160         return compare(value, object.value);
161     }
162 
163     @Override
byteValue()164     public byte byteValue() {
165         return (byte) value;
166     }
167 
168     /**
169      * Returns an integer corresponding to the bits of the given
170      * <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> double precision
171      * {@code value}. All <em>Not-a-Number (NaN)</em> values are converted to a single NaN
172      * representation ({@code 0x7ff8000000000000L}) (compare to {@link #doubleToRawLongBits}).
173      */
doubleToLongBits(double value)174     public static long doubleToLongBits(double value) {
175         if (value != value) {
176             return 0x7ff8000000000000L;  // NaN.
177         } else {
178             return doubleToRawLongBits(value);
179         }
180     }
181 
182     /**
183      * Returns an integer corresponding to the bits of the given
184      * <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> double precision
185      * {@code value}. <em>Not-a-Number (NaN)</em> values are preserved (compare
186      * to {@link #doubleToLongBits}).
187      */
doubleToRawLongBits(double value)188     public static native long doubleToRawLongBits(double value);
189 
190     /**
191      * Gets the primitive value of this double.
192      *
193      * @return this object's primitive value.
194      */
195     @Override
doubleValue()196     public double doubleValue() {
197         return value;
198     }
199 
200     /**
201      * Tests this double for equality with {@code object}.
202      * To be equal, {@code object} must be an instance of {@code Double} and
203      * {@code doubleToLongBits} must give the same value for both objects.
204      *
205      * <p>Note that, unlike {@code ==}, {@code -0.0} and {@code +0.0} compare
206      * unequal, and {@code NaN}s compare equal by this method.
207      *
208      * @param object
209      *            the object to compare this double with.
210      * @return {@code true} if the specified object is equal to this
211      *         {@code Double}; {@code false} otherwise.
212      */
213     @Override
equals(Object object)214     public boolean equals(Object object) {
215         return (object instanceof Double) &&
216                 (doubleToLongBits(this.value) == doubleToLongBits(((Double) object).value));
217     }
218 
219     @Override
floatValue()220     public float floatValue() {
221         return (float) value;
222     }
223 
224     @Override
hashCode()225     public int hashCode() {
226         long v = doubleToLongBits(value);
227         return (int) (v ^ (v >>> 32));
228     }
229 
230     @Override
intValue()231     public int intValue() {
232         return (int) value;
233     }
234 
235     /**
236      * Indicates whether this object represents an infinite value.
237      *
238      * @return {@code true} if the value of this double is positive or negative
239      *         infinity; {@code false} otherwise.
240      */
isInfinite()241     public boolean isInfinite() {
242         return isInfinite(value);
243     }
244 
245     /**
246      * Indicates whether the specified double represents an infinite value.
247      *
248      * @param d
249      *            the double to check.
250      * @return {@code true} if the value of {@code d} is positive or negative
251      *         infinity; {@code false} otherwise.
252      */
isInfinite(double d)253     public static boolean isInfinite(double d) {
254         return (d == POSITIVE_INFINITY) || (d == NEGATIVE_INFINITY);
255     }
256 
257     /**
258      * Indicates whether this object is a <em>Not-a-Number (NaN)</em> value.
259      *
260      * @return {@code true} if this double is <em>Not-a-Number</em>;
261      *         {@code false} if it is a (potentially infinite) double number.
262      */
isNaN()263     public boolean isNaN() {
264         return isNaN(value);
265     }
266 
267     /**
268      * Indicates whether the specified double is a <em>Not-a-Number (NaN)</em>
269      * value.
270      *
271      * @param d
272      *            the double value to check.
273      * @return {@code true} if {@code d} is <em>Not-a-Number</em>;
274      *         {@code false} if it is a (potentially infinite) double number.
275      */
isNaN(double d)276     public static boolean isNaN(double d) {
277         return d != d;
278     }
279 
280     /**
281      * Returns the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a>
282      * double precision float corresponding to the given {@code bits}.
283      */
longBitsToDouble(long bits)284     public static native double longBitsToDouble(long bits);
285 
286     @Override
longValue()287     public long longValue() {
288         return (long) value;
289     }
290 
291     /**
292      * Parses the specified string as a double value.
293      *
294      * @param string
295      *            the string representation of a double value.
296      * @return the primitive double value represented by {@code string}.
297      * @throws NumberFormatException
298      *             if {@code string} cannot be parsed as a double value.
299      */
parseDouble(String string)300     public static double parseDouble(String string) throws NumberFormatException {
301         return StringToReal.parseDouble(string);
302     }
303 
304     @Override
shortValue()305     public short shortValue() {
306         return (short) value;
307     }
308 
309     @Override
toString()310     public String toString() {
311         return Double.toString(value);
312     }
313 
314     /**
315      * Returns a string containing a concise, human-readable description of the
316      * specified double value.
317      *
318      * @param d
319      *             the double to convert to a string.
320      * @return a printable representation of {@code d}.
321      */
toString(double d)322     public static String toString(double d) {
323         return RealToString.getInstance().doubleToString(d);
324     }
325 
326     /**
327      * Parses the specified string as a double value.
328      *
329      * @param string
330      *            the string representation of a double value.
331      * @return a {@code Double} instance containing the double value represented
332      *         by {@code string}.
333      * @throws NumberFormatException
334      *             if {@code string} cannot be parsed as a double value.
335      * @see #parseDouble(String)
336      */
valueOf(String string)337     public static Double valueOf(String string) throws NumberFormatException {
338         return parseDouble(string);
339     }
340 
341     /**
342      * Compares the two specified double values. There are two special cases:
343      * <ul>
344      * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
345      * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
346      * <li>+0.0d is greater than -0.0d</li>
347      * </ul>
348      *
349      * @param double1
350      *            the first value to compare.
351      * @param double2
352      *            the second value to compare.
353      * @return a negative value if {@code double1} is less than {@code double2};
354      *         0 if {@code double1} and {@code double2} are equal; a positive
355      *         value if {@code double1} is greater than {@code double2}.
356      */
compare(double double1, double double2)357     public static int compare(double double1, double double2) {
358         // Non-zero, non-NaN checking.
359         if (double1 > double2) {
360             return 1;
361         }
362         if (double2 > double1) {
363             return -1;
364         }
365         if (double1 == double2 && 0.0d != double1) {
366             return 0;
367         }
368 
369         // NaNs are equal to other NaNs and larger than any other double
370         if (isNaN(double1)) {
371             if (isNaN(double2)) {
372                 return 0;
373             }
374             return 1;
375         } else if (isNaN(double2)) {
376             return -1;
377         }
378 
379         // Deal with +0.0 and -0.0
380         long d1 = doubleToRawLongBits(double1);
381         long d2 = doubleToRawLongBits(double2);
382         // The below expression is equivalent to:
383         // (d1 == d2) ? 0 : (d1 < d2) ? -1 : 1
384         return (int) ((d1 >> 63) - (d2 >> 63));
385     }
386 
387     /**
388      * Returns a {@code Double} instance for the specified double value.
389      *
390      * @param d
391      *            the double value to store in the instance.
392      * @return a {@code Double} instance containing {@code d}.
393      * @since 1.5
394      */
valueOf(double d)395     public static Double valueOf(double d) {
396         return new Double(d);
397     }
398 
399     /**
400      * Converts the specified double into its hexadecimal string representation.
401      *
402      * @param d
403      *            the double to convert.
404      * @return the hexadecimal string representation of {@code d}.
405      * @since 1.5
406      */
toHexString(double d)407     public static String toHexString(double d) {
408         /*
409          * Reference: http://en.wikipedia.org/wiki/IEEE_754-1985
410          */
411         if (d != d) {
412             return "NaN";
413         }
414         if (d == POSITIVE_INFINITY) {
415             return "Infinity";
416         }
417         if (d == NEGATIVE_INFINITY) {
418             return "-Infinity";
419         }
420 
421         long bitValue = doubleToLongBits(d);
422 
423         boolean negative = (bitValue & 0x8000000000000000L) != 0;
424         // mask exponent bits and shift down
425         long exponent = (bitValue & 0x7FF0000000000000L) >>> 52;
426         // mask significand bits and shift up
427         long significand = bitValue & 0x000FFFFFFFFFFFFFL;
428 
429         if (exponent == 0 && significand == 0) {
430             return (negative ? "-0x0.0p0" : "0x0.0p0");
431         }
432 
433         StringBuilder hexString = new StringBuilder(10);
434         if (negative) {
435             hexString.append("-0x");
436         } else {
437             hexString.append("0x");
438         }
439 
440         if (exponent == 0) { // denormal (subnormal) value
441             hexString.append("0.");
442             // significand is 52-bits, so there can be 13 hex digits
443             int fractionDigits = 13;
444             // remove trailing hex zeros, so Integer.toHexString() won't print
445             // them
446             while ((significand != 0) && ((significand & 0xF) == 0)) {
447                 significand >>>= 4;
448                 fractionDigits--;
449             }
450             // this assumes Integer.toHexString() returns lowercase characters
451             String hexSignificand = Long.toHexString(significand);
452 
453             // if there are digits left, then insert some '0' chars first
454             if (significand != 0 && fractionDigits > hexSignificand.length()) {
455                 int digitDiff = fractionDigits - hexSignificand.length();
456                 while (digitDiff-- != 0) {
457                     hexString.append('0');
458                 }
459             }
460             hexString.append(hexSignificand);
461             hexString.append("p-1022");
462         } else { // normal value
463             hexString.append("1.");
464             // significand is 52-bits, so there can be 13 hex digits
465             int fractionDigits = 13;
466             // remove trailing hex zeros, so Integer.toHexString() won't print
467             // them
468             while ((significand != 0) && ((significand & 0xF) == 0)) {
469                 significand >>>= 4;
470                 fractionDigits--;
471             }
472             // this assumes Integer.toHexString() returns lowercase characters
473             String hexSignificand = Long.toHexString(significand);
474 
475             // if there are digits left, then insert some '0' chars first
476             if (significand != 0 && fractionDigits > hexSignificand.length()) {
477                 int digitDiff = fractionDigits - hexSignificand.length();
478                 while (digitDiff-- != 0) {
479                     hexString.append('0');
480                 }
481             }
482 
483             hexString.append(hexSignificand);
484             hexString.append('p');
485             // remove exponent's 'bias' and convert to a string
486             hexString.append(Long.toString(exponent - 1023));
487         }
488         return hexString.toString();
489     }
490 }
491