1 /* Double.java -- object wrapper for double
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
42 * Instances of class <code>Double</code> represent primitive
43 * <code>double</code> values.
45 * Additionally, this class provides various helper functions and variables
49 * @author Andrew Haley (aph@cygnus.com)
50 * @author Eric Blake (ebb9@email.byu.edu)
51 * @author Tom Tromey (tromey@redhat.com)
52 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
54 * @status partly updated to 1.5
57 @METHODDEFAULT("OUT<THIS,THIS<IN,THISLOC=THIS,RETURNLOC=OUT")
58 public final class Double extends Number // implements Comparable<Double>
61 * Compatible with JDK 1.0+.
64 * The immutable value of this Double.
66 * @serial the wrapped double
69 private final double value;
72 * Create a <code>Double</code> from the primitive <code>double</code>
76 * the <code>double</code> argument
78 public Double(double value) {
83 * Create a <code>Double</code> from the specified <code>String</code>. This
84 * method calls <code>Double.parseDouble()</code>.
87 * the <code>String</code> to convert
88 * @throws NumberFormatException
89 * if <code>s</code> cannot be parsed as a <code>double</code>
90 * @throws NullPointerException
91 * if <code>s</code> is null
92 * @see #parseDouble(String)
94 public Double(String s) {
95 value = parseDouble(s);
99 * Convert the <code>double</code> to a <code>String</code>. Floating-point
100 * string representation is fairly complex: here is a rundown of the possible
101 * values. "<code>[-]</code>" indicates that a negative sign will be printed
102 * if the value (or exponent) is negative. "<code><number></code>" means
103 * a string of digits ('0' to '9'). "<code><digit></code>" means a
104 * single digit ('0' to '9').<br>
108 * <th>Value of Double</th>
109 * <th>String Representation</th>
113 * <td><code>[-]0.0</code></td>
116 * <td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
117 * <td><code>[-]number.number</code></td>
120 * <td>Other numeric value</td>
121 * <td><code>[-]<digit>.<number>
122 * E[-]<number></code></td>
125 * <td>[+-] infinity</td>
126 * <td><code>[-]Infinity</code></td>
130 * <td><code>NaN</code></td>
134 * Yes, negative zero <em>is</em> a possible value. Note that there is
135 * <em>always</em> a <code>.</code> and at least one digit printed after it:
136 * even if the number is 3, it will be printed as <code>3.0</code>. After the
137 * ".", all digits will be printed except trailing zeros. The result is
138 * rounded to the shortest decimal number which will parse back to the same
142 * To create other output formats, use {@link java.text.NumberFormat}.
144 * @XXX specify where we are not in accord with the spec.
147 * the <code>double</code> to convert
148 * @return the <code>String</code> representing the <code>double</code>
150 public static String toString(@LOC("IN") double d) {
151 return String.valueOf(d);
155 * Convert a double value to a hexadecimal string. This converts as follows:
157 * <li>A NaN value is converted to the string "NaN".
158 * <li>Positive infinity is converted to the string "Infinity".
159 * <li>Negative infinity is converted to the string "-Infinity".
160 * <li>For all other values, the first character of the result is '-' if the
161 * value is negative. This is followed by '0x1.' if the value is normal, and
162 * '0x0.' if the value is denormal. This is then followed by a (lower-case)
163 * hexadecimal representation of the mantissa, with leading zeros as required
164 * for denormal values. The next character is a 'p', and this is followed by a
165 * decimal representation of the unbiased exponent.
170 * @return the hexadecimal string representation
173 public static String toHexString(double d) {
175 * if (isNaN(d)) return "NaN"; if (isInfinite(d)) return d < 0 ? "-Infinity"
178 * long bits = doubleToLongBits(d); StringBuilder result = new
181 * if (bits < 0) result.append('-'); result.append("0x");
183 * final int mantissaBits = 52; final int exponentBits = 11; long mantMask =
184 * (1L << mantissaBits) - 1; long mantissa = bits & mantMask; long expMask =
185 * (1L << exponentBits) - 1; long exponent = (bits >>> mantissaBits) &
188 * result.append(exponent == 0 ? '0' : '1'); result.append('.');
189 * result.append(Long.toHexString(mantissa)); if (exponent == 0 && mantissa
190 * != 0) { // Treat denormal specially by inserting '0's to make // the
191 * length come out right. The constants here are // to account for things
192 * like the '0x'. int offset = 4 + ((bits < 0) ? 1 : 0); // The silly +3 is
193 * here to keep the code the same between // the Float and Double cases. In
194 * Float the value is // not a multiple of 4. int desiredLength = offset +
195 * (mantissaBits + 3) / 4; while (result.length() < desiredLength)
196 * result.insert(offset, '0'); } result.append('p'); if (exponent == 0 &&
197 * mantissa == 0) { // Zero, so do nothing special. } else { // Apply bias.
198 * boolean denormal = exponent == 0; exponent -= (1 << (exponentBits - 1)) -
199 * 1; // Handle denormal. if (denormal) ++exponent; }
201 * result.append(Long.toString(exponent)); return result.toString();
207 * Returns a <code>Double</code> object wrapping the value. In contrast to the
208 * <code>Double</code> constructor, this method may cache some values. It is
209 * used by boxing conversion.
213 * @return the <code>Double</code>
216 public static Double valueOf(double val) {
217 // We don't actually cache, but we could.
218 return new Double(val);
222 * Create a new <code>Double</code> object using the <code>String</code>.
225 * the <code>String</code> to convert
226 * @return the new <code>Double</code>
227 * @throws NumberFormatException
228 * if <code>s</code> cannot be parsed as a <code>double</code>
229 * @throws NullPointerException
230 * if <code>s</code> is null.
231 * @see #parseDouble(String)
233 public static Double valueOf(String s) {
234 return new Double(parseDouble(s));
238 * Parse the specified <code>String</code> as a <code>double</code>. The
239 * extended BNF grammar is as follows:<br>
242 * <em>DecodableString</em>:
243 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
244 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
245 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
246 * [ <code>f</code> | <code>F</code> | <code>d</code>
247 * | <code>D</code>] )
248 * <em>FloatingPoint</em>:
249 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
250 * [ <em>Exponent</em> ] )
251 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
253 * ( ( <code>e</code> | <code>E</code> )
254 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
255 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
259 * NaN and infinity are special cases, to allow parsing of the output of
260 * toString. Otherwise, the result is determined by calculating
261 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding to
262 * the nearest double. Remember that many numbers cannot be precisely
263 * represented in floating point. In case of overflow, infinity is used, and
264 * in case of underflow, signed zero is used. Unlike Integer.parseInt, this
265 * does not accept Unicode digits outside the ASCII range.
268 * If an unexpected character is found in the <code>String</code>, a
269 * <code>NumberFormatException</code> will be thrown. Leading and trailing
270 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces internal
271 * to the actual number are not allowed.
274 * To parse numbers according to another format, consider using
275 * {@link java.text.NumberFormat}.
277 * @XXX specify where/how we are not in accord with the spec.
280 * the <code>String</code> to convert
281 * @return the <code>double</code> value of <code>s</code>
282 * @throws NumberFormatException
283 * if <code>s</code> cannot be parsed as a <code>double</code>
284 * @throws NullPointerException
285 * if <code>s</code> is null
288 * @see #POSITIVE_INFINITY
289 * @see #NEGATIVE_INFINITY
292 public static double parseDouble(String str) {
293 return nativeparsedouble(str);
296 public static native double nativeparsedouble(String str);
298 public static native double nativeparsedouble(int start, int length, byte[] str);
301 * Return <code>true</code> if the <code>double</code> has the same value as
302 * <code>NaN</code>, otherwise return <code>false</code>.
305 * the <code>double</code> to compare
306 * @return whether the argument is <code>NaN</code>.
308 public static boolean isNaN(@LOC("IN") double v) {
309 // This works since NaN != NaN is the only reflexive inequality
310 // comparison which returns true.
315 * Return <code>true</code> if the <code>double</code> has a value equal to
316 * either <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
317 * otherwise return <code>false</code>.
320 * the <code>double</code> to compare
321 * @return whether the argument is (-/+) infinity.
323 public static boolean isInfinite(double v) {
328 * Return <code>true</code> if the value of this <code>Double</code> is the
329 * same as <code>NaN</code>, otherwise return <code>false</code>.
331 * @return whether this <code>Double</code> is <code>NaN</code>
333 public boolean isNaN() {
338 * Return <code>true</code> if the value of this <code>Double</code> is the
339 * same as <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
340 * otherwise return <code>false</code>.
342 * @return whether this <code>Double</code> is (-/+) infinity
344 public boolean isInfinite() {
345 return isInfinite(value);
349 * Convert the <code>double</code> value of this <code>Double</code> to a
350 * <code>String</code>. This method calls <code>Double.toString(double)</code>
351 * to do its dirty work.
353 * @return the <code>String</code> representation
354 * @see #toString(double)
356 public String toString() {
357 return toString(value);
361 * Return the value of this <code>Double</code> as a <code>byte</code>.
363 * @return the byte value
366 public byte byteValue() {
371 * Return the value of this <code>Double</code> as a <code>short</code>.
373 * @return the short value
376 public short shortValue() {
377 return (short) value;
381 * Return the value of this <code>Double</code> as an <code>int</code>.
383 * @return the int value
385 public int intValue() {
390 * Return the value of this <code>Double</code> as a <code>long</code>.
392 * @return the long value
394 public long longValue() {
399 * Return the value of this <code>Double</code> as a <code>float</code>.
401 * @return the float value
403 public float floatValue() {
404 return (float) value;
408 * Return the value of this <code>Double</code>.
410 * @return the double value
412 public double doubleValue() {
417 * Return a hashcode representing this Object. <code>Double</code>'s hash code
418 * is calculated by:<br>
419 * <code>long v = Double.doubleToLongBits(doubleValue());<br>
420 * int hash = (int)(v^(v>>32))</code>.
422 * @return this Object's hash code
423 * @see #doubleToLongBits(double)
425 public int hashCode() {
426 @LOC("OUT") long v = doubleToLongBits(value);
427 return (int) (v ^ (v >>> 32));
431 * Returns <code>true</code> if <code>obj</code> is an instance of
432 * <code>Double</code> and represents the same double value. Unlike comparing
433 * two doubles with <code>==</code>, this treats two instances of
434 * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
435 * <code>-0.0</code> as unequal.
438 * Note that <code>d1.equals(d2)</code> is identical to
439 * <code>doubleToLongBits(d1.doubleValue()) ==
440 * doubleToLongBits(d2.doubleValue())</code>.
443 * the object to compare
444 * @return whether the objects are semantically equal
446 public boolean equals(Object obj) {
447 if (!(obj instanceof Double))
450 double d = ((Double) obj).value;
452 // Avoid call to native method. However, some implementations, like gcj,
453 // are better off using floatToIntBits(value) == floatToIntBits(f).
454 // Check common case first, then check NaN and 0.
456 return (value != 0) || (1 / value == 1 / d);
457 return isNaN(value) && isNaN(d);
461 * Convert the double to the IEEE 754 floating-point "double format" bit
462 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52 (masked
463 * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
464 * 0x000fffffffffffffL) are the mantissa. This function collapses all versions
465 * of NaN to 0x7ff8000000000000L. The result of this function can be used as
466 * the argument to <code>Double.longBitsToDouble(long)</code> to obtain the
467 * original <code>double</code> value.
470 * the <code>double</code> to convert
471 * @return the bits of the <code>double</code>
472 * @see #longBitsToDouble(long)
474 public static long doubleToLongBits(@LOC("IN") double value) {
476 return 0x7ff8000000000000L;
478 return /* VMDouble. */doubleToRawLongBits(value);
482 * Convert the double to the IEEE 754 floating-point "double format" bit
483 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52 (masked
484 * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
485 * 0x000fffffffffffffL) are the mantissa. This function leaves NaN alone,
486 * rather than collapsing to a canonical value. The result of this function
487 * can be used as the argument to <code>Double.longBitsToDouble(long)</code>
488 * to obtain the original <code>double</code> value.
491 * the <code>double</code> to convert
492 * @return the bits of the <code>double</code>
493 * @see #longBitsToDouble(long)
496 * public static long doubleToRawLongBits(double value) { return
497 * VMDouble.doubleToRawLongBits(value); }
499 public static native long doubleToRawLongBits(double value);
502 * Convert the argument in IEEE 754 floating-point "double format" bit layout
503 * to the corresponding float. Bit 63 (the most significant) is the sign bit,
504 * bits 62-52 (masked by 0x7ff0000000000000L) represent the exponent, and bits
505 * 51-0 (masked by 0x000fffffffffffffL) are the mantissa. This function leaves
506 * NaN alone, so that you can recover the bit pattern with
507 * <code>Double.doubleToRawLongBits(double)</code>.
510 * the bits to convert
511 * @return the <code>double</code> represented by the bits
512 * @see #doubleToLongBits(double)
513 * @see #doubleToRawLongBits(double)
516 * public static double longBitsToDouble(long bits) { return
517 * VMDouble.longBitsToDouble(bits); }
519 public static native double longBitsToDouble(long bits);
522 * Compare two Doubles numerically by comparing their <code>double</code>
523 * values. The result is positive if the first is greater, negative if the
524 * second is greater, and 0 if the two are equal. However, this special cases
525 * NaN and signed zero as follows: NaN is considered greater than all other
526 * doubles, including <code>POSITIVE_INFINITY</code>, and positive zero is
527 * considered greater than negative zero.
530 * the Double to compare
531 * @return the comparison
534 public int compareTo(Double d) {
535 return compare(value, d.value);
539 * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in other
540 * words this compares two doubles, special casing NaN and zero, without the
541 * overhead of objects.
544 * the first double to compare
546 * the second double to compare
547 * @return the comparison
550 public static int compare(double x, double y) {
551 // handle the easy cases:
557 // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
558 long lx = doubleToRawLongBits(x);
559 long ly = doubleToRawLongBits(y);
565 return (y != y) ? 0 : 1;
570 return (lx < ly) ? -1 : 1;