• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 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 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 
105     // Note: This can't be set to "double.class", since *that* is
106     // defined to be "java.lang.Double.TYPE";
107 
108     /**
109      * Constant for the number of bits needed to represent a {@code double} in
110      * two's complement form.
111      *
112      * @since 1.5
113      */
114     public static final int SIZE = 64;
115 
116     /**
117      * Constructs a new {@code Double} with the specified primitive double
118      * value.
119      *
120      * @param value
121      *            the primitive double value to store in the new instance.
122      */
Double(double value)123     public Double(double value) {
124         this.value = value;
125     }
126 
127     /**
128      * Constructs a new {@code Double} from the specified string.
129      *
130      * @param string
131      *            the string representation of a double value.
132      * @throws NumberFormatException
133      *             if {@code string} can not be decoded into a double value.
134      * @see #parseDouble(String)
135      */
Double(String string)136     public Double(String string) throws NumberFormatException {
137         this(parseDouble(string));
138     }
139 
140     /**
141      * Compares this object to the specified double object to determine their
142      * relative order. There are two special cases:
143      * <ul>
144      * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
145      * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
146      * <li>+0.0d is greater than -0.0d</li>
147      * </ul>
148      *
149      * @param object
150      *            the double object to compare this object to.
151      * @return a negative value if the value of this double is less than the
152      *         value of {@code object}; 0 if the value of this double and the
153      *         value of {@code object} are equal; a positive value if the value
154      *         of this double is greater than the value of {@code object}.
155      * @throws NullPointerException
156      *             if {@code object} is {@code null}.
157      * @see java.lang.Comparable
158      * @since 1.2
159      */
compareTo(Double object)160     public int compareTo(Double object) {
161         return compare(value, object.value);
162     }
163 
164     @Override
byteValue()165     public byte byteValue() {
166         return (byte) value;
167     }
168 
169     /**
170      * Converts the specified double value to a binary representation conforming
171      * to the IEEE 754 floating-point double precision bit layout. All
172      * <em>Not-a-Number (NaN)</em> values are converted to a single NaN
173      * representation ({@code 0x7ff8000000000000L}).
174      *
175      * @param value
176      *            the double value to convert.
177      * @return the IEEE 754 floating-point double precision representation of
178      *         {@code value}.
179      * @see #doubleToRawLongBits(double)
180      * @see #longBitsToDouble(long)
181      */
doubleToLongBits(double value)182     public static native long doubleToLongBits(double value);
183 
184     /**
185      * Converts the specified double value to a binary representation conforming
186      * to the IEEE 754 floating-point double precision bit layout.
187      * <em>Not-a-Number (NaN)</em> values are preserved.
188      *
189      * @param value
190      *            the double value to convert.
191      * @return the IEEE 754 floating-point double precision representation of
192      *         {@code value}.
193      * @see #doubleToLongBits(double)
194      * @see #longBitsToDouble(long)
195      */
doubleToRawLongBits(double value)196     public static native long doubleToRawLongBits(double value);
197 
198     /**
199      * Gets the primitive value of this double.
200      *
201      * @return this object's primitive value.
202      */
203     @Override
doubleValue()204     public double doubleValue() {
205         return value;
206     }
207 
208     /**
209      * Tests this double for equality with {@code object}.
210      * To be equal, {@code object} must be an instance of {@code Double} and
211      * {@code doubleToLongBits} must give the same value for both objects.
212      *
213      * <p>Note that, unlike {@code ==}, {@code -0.0} and {@code +0.0} compare
214      * unequal, and {@code NaN}s compare equal by this method.
215      *
216      * @param object
217      *            the object to compare this double with.
218      * @return {@code true} if the specified object is equal to this
219      *         {@code Double}; {@code false} otherwise.
220      */
221     @Override
equals(Object object)222     public boolean equals(Object object) {
223         return (object == this)
224                 || (object instanceof Double)
225                 && (doubleToLongBits(this.value) == doubleToLongBits(((Double) object).value));
226     }
227 
228     @Override
floatValue()229     public float floatValue() {
230         return (float) value;
231     }
232 
233     @Override
hashCode()234     public int hashCode() {
235         long v = doubleToLongBits(value);
236         return (int) (v ^ (v >>> 32));
237     }
238 
239     @Override
intValue()240     public int intValue() {
241         return (int) value;
242     }
243 
244     /**
245      * Indicates whether this object represents an infinite value.
246      *
247      * @return {@code true} if the value of this double is positive or negative
248      *         infinity; {@code false} otherwise.
249      */
isInfinite()250     public boolean isInfinite() {
251         return isInfinite(value);
252     }
253 
254     /**
255      * Indicates whether the specified double represents an infinite value.
256      *
257      * @param d
258      *            the double to check.
259      * @return {@code true} if the value of {@code d} is positive or negative
260      *         infinity; {@code false} otherwise.
261      */
isInfinite(double d)262     public static boolean isInfinite(double d) {
263         return (d == POSITIVE_INFINITY) || (d == NEGATIVE_INFINITY);
264     }
265 
266     /**
267      * Indicates whether this object is a <em>Not-a-Number (NaN)</em> value.
268      *
269      * @return {@code true} if this double is <em>Not-a-Number</em>;
270      *         {@code false} if it is a (potentially infinite) double number.
271      */
isNaN()272     public boolean isNaN() {
273         return isNaN(value);
274     }
275 
276     /**
277      * Indicates whether the specified double is a <em>Not-a-Number (NaN)</em>
278      * value.
279      *
280      * @param d
281      *            the double value to check.
282      * @return {@code true} if {@code d} is <em>Not-a-Number</em>;
283      *         {@code false} if it is a (potentially infinite) double number.
284      */
isNaN(double d)285     public static boolean isNaN(double d) {
286         return d != d;
287     }
288 
289     /**
290      * Converts the specified IEEE 754 floating-point double precision bit
291      * pattern to a Java double value.
292      *
293      * @param bits
294      *            the IEEE 754 floating-point double precision representation of
295      *            a double value.
296      * @return the double value converted from {@code bits}.
297      * @see #doubleToLongBits(double)
298      * @see #doubleToRawLongBits(double)
299      */
longBitsToDouble(long bits)300     public static native double longBitsToDouble(long bits);
301 
302     @Override
longValue()303     public long longValue() {
304         return (long) value;
305     }
306 
307     /**
308      * Parses the specified string as a double value.
309      *
310      * @param string
311      *            the string representation of a double value.
312      * @return the primitive double value represented by {@code string}.
313      * @throws NumberFormatException
314      *             if {@code string} is {@code null}, has a length of zero or
315      *             can not be parsed as a double value.
316      */
parseDouble(String string)317     public static double parseDouble(String string) throws NumberFormatException {
318         return org.apache.harmony.luni.util.FloatingPointParser.parseDouble(string);
319     }
320 
321     @Override
shortValue()322     public short shortValue() {
323         return (short) value;
324     }
325 
326     @Override
toString()327     public String toString() {
328         return Double.toString(value);
329     }
330 
331     /**
332      * Returns a string containing a concise, human-readable description of the
333      * specified double value.
334      *
335      * @param d
336      *             the double to convert to a string.
337      * @return a printable representation of {@code d}.
338      */
toString(double d)339     public static String toString(double d) {
340         return RealToString.getInstance().doubleToString(d);
341     }
342 
343     /**
344      * Parses the specified string as a double value.
345      *
346      * @param string
347      *            the string representation of a double value.
348      * @return a {@code Double} instance containing the double value represented
349      *         by {@code string}.
350      * @throws NumberFormatException
351      *             if {@code string} is {@code null}, has a length of zero or
352      *             can not be parsed as a double value.
353      * @see #parseDouble(String)
354      */
valueOf(String string)355     public static Double valueOf(String string) throws NumberFormatException {
356         return parseDouble(string);
357     }
358 
359     /**
360      * Compares the two specified double values. There are two special cases:
361      * <ul>
362      * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
363      * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
364      * <li>+0.0d is greater than -0.0d</li>
365      * </ul>
366      *
367      * @param double1
368      *            the first value to compare.
369      * @param double2
370      *            the second value to compare.
371      * @return a negative value if {@code double1} is less than {@code double2};
372      *         0 if {@code double1} and {@code double2} are equal; a positive
373      *         value if {@code double1} is greater than {@code double2}.
374      */
compare(double double1, double double2)375     public static int compare(double double1, double double2) {
376         // Non-zero, non-NaN checking.
377         if (double1 > double2) {
378             return 1;
379         }
380         if (double2 > double1) {
381             return -1;
382         }
383         if (double1 == double2 && 0.0d != double1) {
384             return 0;
385         }
386 
387         // NaNs are equal to other NaNs and larger than any other double
388         if (isNaN(double1)) {
389             if (isNaN(double2)) {
390                 return 0;
391             }
392             return 1;
393         } else if (isNaN(double2)) {
394             return -1;
395         }
396 
397         // Deal with +0.0 and -0.0
398         long d1 = doubleToRawLongBits(double1);
399         long d2 = doubleToRawLongBits(double2);
400         // The below expression is equivalent to:
401         // (d1 == d2) ? 0 : (d1 < d2) ? -1 : 1
402         return (int) ((d1 >> 63) - (d2 >> 63));
403     }
404 
405     /**
406      * Returns a {@code Double} instance for the specified double value.
407      *
408      * @param d
409      *            the double value to store in the instance.
410      * @return a {@code Double} instance containing {@code d}.
411      * @since 1.5
412      */
valueOf(double d)413     public static Double valueOf(double d) {
414         return new Double(d);
415     }
416 
417     /**
418      * Converts the specified double into its hexadecimal string representation.
419      *
420      * @param d
421      *            the double to convert.
422      * @return the hexadecimal string representation of {@code d}.
423      * @since 1.5
424      */
toHexString(double d)425     public static String toHexString(double d) {
426         /*
427          * Reference: http://en.wikipedia.org/wiki/IEEE_754
428          */
429         if (d != d) {
430             return "NaN";
431         }
432         if (d == POSITIVE_INFINITY) {
433             return "Infinity";
434         }
435         if (d == NEGATIVE_INFINITY) {
436             return "-Infinity";
437         }
438 
439         long bitValue = doubleToLongBits(d);
440 
441         boolean negative = (bitValue & 0x8000000000000000L) != 0;
442         // mask exponent bits and shift down
443         long exponent = (bitValue & 0x7FF0000000000000L) >>> 52;
444         // mask significand bits and shift up
445         long significand = bitValue & 0x000FFFFFFFFFFFFFL;
446 
447         if (exponent == 0 && significand == 0) {
448             return (negative ? "-0x0.0p0" : "0x0.0p0");
449         }
450 
451         StringBuilder hexString = new StringBuilder(10);
452         if (negative) {
453             hexString.append("-0x");
454         } else {
455             hexString.append("0x");
456         }
457 
458         if (exponent == 0) { // denormal (subnormal) value
459             hexString.append("0.");
460             // significand is 52-bits, so there can be 13 hex digits
461             int fractionDigits = 13;
462             // remove trailing hex zeros, so Integer.toHexString() won't print
463             // them
464             while ((significand != 0) && ((significand & 0xF) == 0)) {
465                 significand >>>= 4;
466                 fractionDigits--;
467             }
468             // this assumes Integer.toHexString() returns lowercase characters
469             String hexSignificand = Long.toHexString(significand);
470 
471             // if there are digits left, then insert some '0' chars first
472             if (significand != 0 && fractionDigits > hexSignificand.length()) {
473                 int digitDiff = fractionDigits - hexSignificand.length();
474                 while (digitDiff-- != 0) {
475                     hexString.append('0');
476                 }
477             }
478             hexString.append(hexSignificand);
479             hexString.append("p-1022");
480         } else { // normal value
481             hexString.append("1.");
482             // significand is 52-bits, so there can be 13 hex digits
483             int fractionDigits = 13;
484             // remove trailing hex zeros, so Integer.toHexString() won't print
485             // them
486             while ((significand != 0) && ((significand & 0xF) == 0)) {
487                 significand >>>= 4;
488                 fractionDigits--;
489             }
490             // this assumes Integer.toHexString() returns lowercase characters
491             String hexSignificand = Long.toHexString(significand);
492 
493             // if there are digits left, then insert some '0' chars first
494             if (significand != 0 && fractionDigits > hexSignificand.length()) {
495                 int digitDiff = fractionDigits - hexSignificand.length();
496                 while (digitDiff-- != 0) {
497                     hexString.append('0');
498                 }
499             }
500 
501             hexString.append(hexSignificand);
502             hexString.append('p');
503             // remove exponent's 'bias' and convert to a string
504             hexString.append(Long.toString(exponent - 1023));
505         }
506         return hexString.toString();
507     }
508 }
509