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. */
43 * Instances of class <code>Double</code> represent primitive
44 * <code>double</code> values.
46 * Additionally, this class provides various helper functions and variables
50 * @author Andrew Haley (aph@cygnus.com)
51 * @author Eric Blake (ebb9@email.byu.edu)
52 * @author Tom Tromey (tromey@redhat.com)
53 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
55 * @status partly updated to 1.5
57 public final class Double extends Number //implements Comparable<Double>
60 * Compatible with JDK 1.0+.
63 * The immutable value of this Double.
65 * @serial the wrapped double
67 private final double value;
70 * Create a <code>Double</code> from the primitive <code>double</code>
73 * @param value the <code>double</code> argument
75 public Double(double value) {
80 * Create a <code>Double</code> from the specified <code>String</code>.
81 * This method calls <code>Double.parseDouble()</code>.
83 * @param s the <code>String</code> to convert
84 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
86 * @throws NullPointerException if <code>s</code> is null
87 * @see #parseDouble(String)
89 public Double(String s) {
90 value = parseDouble(s);
94 * Convert the <code>double</code> to a <code>String</code>.
95 * Floating-point string representation is fairly complex: here is a
96 * rundown of the possible values. "<code>[-]</code>" indicates that a
97 * negative sign will be printed if the value (or exponent) is negative.
98 * "<code><number></code>" means a string of digits ('0' to '9').
99 * "<code><digit></code>" means a single digit ('0' to '9').<br>
102 * <tr><th>Value of Double</th><th>String Representation</th></tr>
103 * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
104 * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
105 * <td><code>[-]number.number</code></td></tr>
106 * <tr><td>Other numeric value</td>
107 * <td><code>[-]<digit>.<number>
108 * E[-]<number></code></td></tr>
109 * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
110 * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
113 * Yes, negative zero <em>is</em> a possible value. Note that there is
114 * <em>always</em> a <code>.</code> and at least one digit printed after
115 * it: even if the number is 3, it will be printed as <code>3.0</code>.
116 * After the ".", all digits will be printed except trailing zeros. The
117 * result is rounded to the shortest decimal number which will parse back
118 * to the same double.
120 * <p>To create other output formats, use {@link java.text.NumberFormat}.
122 * @XXX specify where we are not in accord with the spec.
124 * @param d the <code>double</code> to convert
125 * @return the <code>String</code> representing the <code>double</code>
127 public static String toString(double d) {
128 return String.valueOf(d);
132 * Convert a double value to a hexadecimal string. This converts as
135 * <li> A NaN value is converted to the string "NaN".
136 * <li> Positive infinity is converted to the string "Infinity".
137 * <li> Negative infinity is converted to the string "-Infinity".
138 * <li> For all other values, the first character of the result is '-'
139 * if the value is negative. This is followed by '0x1.' if the
140 * value is normal, and '0x0.' if the value is denormal. This is
141 * then followed by a (lower-case) hexadecimal representation of the
142 * mantissa, with leading zeros as required for denormal values.
143 * The next character is a 'p', and this is followed by a decimal
144 * representation of the unbiased exponent.
146 * @param d the double value
147 * @return the hexadecimal string representation
150 public static String toHexString(double d) {
155 return d < 0 ? "-Infinity" : "Infinity";
157 long bits = doubleToLongBits(d);
158 StringBuilder result = new StringBuilder();
164 final int mantissaBits = 52;
165 final int exponentBits = 11;
166 long mantMask = (1L << mantissaBits) - 1;
167 long mantissa = bits & mantMask;
168 long expMask = (1L << exponentBits) - 1;
169 long exponent = (bits >>> mantissaBits) & expMask;
171 result.append(exponent == 0 ? '0' : '1');
173 result.append(Long.toHexString(mantissa));
174 if (exponent == 0 && mantissa != 0)
176 // Treat denormal specially by inserting '0's to make
177 // the length come out right. The constants here are
178 // to account for things like the '0x'.
179 int offset = 4 + ((bits < 0) ? 1 : 0);
180 // The silly +3 is here to keep the code the same between
181 // the Float and Double cases. In Float the value is
182 // not a multiple of 4.
183 int desiredLength = offset + (mantissaBits + 3) / 4;
184 while (result.length() < desiredLength)
185 result.insert(offset, '0');
188 if (exponent == 0 && mantissa == 0)
190 // Zero, so do nothing special.
195 boolean denormal = exponent == 0;
196 exponent -= (1 << (exponentBits - 1)) - 1;
202 result.append(Long.toString(exponent));
203 return result.toString();
209 * Returns a <code>Double</code> object wrapping the value.
210 * In contrast to the <code>Double</code> constructor, this method
211 * may cache some values. It is used by boxing conversion.
213 * @param val the value to wrap
214 * @return the <code>Double</code>
217 public static Double valueOf(double val) {
218 // We don't actually cache, but we could.
219 return new Double(val);
223 * Create a new <code>Double</code> object using the <code>String</code>.
225 * @param s the <code>String</code> to convert
226 * @return the new <code>Double</code>
227 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
228 * <code>double</code>
229 * @throws NullPointerException if <code>s</code> is null.
230 * @see #parseDouble(String)
232 public static Double valueOf(String s) {
233 return new Double(parseDouble(s));
237 * Parse the specified <code>String</code> as a <code>double</code>. The
238 * extended BNF grammar is as follows:<br>
240 * <em>DecodableString</em>:
241 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
242 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
243 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
244 * [ <code>f</code> | <code>F</code> | <code>d</code>
245 * | <code>D</code>] )
246 * <em>FloatingPoint</em>:
247 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
248 * [ <em>Exponent</em> ] )
249 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
251 * ( ( <code>e</code> | <code>E</code> )
252 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
253 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
256 * <p>NaN and infinity are special cases, to allow parsing of the output
257 * of toString. Otherwise, the result is determined by calculating
258 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
259 * to the nearest double. Remember that many numbers cannot be precisely
260 * represented in floating point. In case of overflow, infinity is used,
261 * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
262 * this does not accept Unicode digits outside the ASCII range.
264 * <p>If an unexpected character is found in the <code>String</code>, a
265 * <code>NumberFormatException</code> will be thrown. Leading and trailing
266 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
267 * internal to the actual number are not allowed.
269 * <p>To parse numbers according to another format, consider using
270 * {@link java.text.NumberFormat}.
272 * @XXX specify where/how we are not in accord with the spec.
274 * @param str the <code>String</code> to convert
275 * @return the <code>double</code> value of <code>s</code>
276 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
277 * <code>double</code>
278 * @throws NullPointerException if <code>s</code> is null
281 * @see #POSITIVE_INFINITY
282 * @see #NEGATIVE_INFINITY
285 public static double parseDouble(String str) {
286 return nativeparsedouble(str);
289 public static native double nativeparsedouble(String str);
293 * Return <code>true</code> if the <code>double</code> has the same
294 * value as <code>NaN</code>, otherwise return <code>false</code>.
296 * @param v the <code>double</code> to compare
297 * @return whether the argument is <code>NaN</code>.
299 public static boolean isNaN(double v) {
300 // This works since NaN != NaN is the only reflexive inequality
301 // comparison which returns true.
306 * Return <code>true</code> if the <code>double</code> has a value
307 * equal to either <code>NEGATIVE_INFINITY</code> or
308 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
310 * @param v the <code>double</code> to compare
311 * @return whether the argument is (-/+) infinity.
313 public static boolean isInfinite(double v) {
318 * Return <code>true</code> if the value of this <code>Double</code>
319 * is the same as <code>NaN</code>, otherwise return <code>false</code>.
321 * @return whether this <code>Double</code> is <code>NaN</code>
323 public boolean isNaN()
329 * Return <code>true</code> if the value of this <code>Double</code>
330 * is the same as <code>NEGATIVE_INFINITY</code> or
331 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
333 * @return whether this <code>Double</code> is (-/+) infinity
335 public boolean isInfinite()
337 return isInfinite(value);
341 * Convert the <code>double</code> value of this <code>Double</code>
342 * to a <code>String</code>. This method calls
343 * <code>Double.toString(double)</code> to do its dirty work.
345 * @return the <code>String</code> representation
346 * @see #toString(double)
348 public String toString()
350 return toString(value);
354 * Return the value of this <code>Double</code> as a <code>byte</code>.
356 * @return the byte value
359 public byte byteValue()
365 * Return the value of this <code>Double</code> as a <code>short</code>.
367 * @return the short value
370 public short shortValue()
372 return (short) value;
376 * Return the value of this <code>Double</code> as an <code>int</code>.
378 * @return the int value
380 public int intValue()
386 * Return the value of this <code>Double</code> as a <code>long</code>.
388 * @return the long value
390 public long longValue()
396 * Return the value of this <code>Double</code> as a <code>float</code>.
398 * @return the float value
400 public float floatValue()
402 return (float) value;
406 * Return the value of this <code>Double</code>.
408 * @return the double value
410 public double doubleValue()
416 * Return a hashcode representing this Object. <code>Double</code>'s hash
417 * code is calculated by:<br>
418 * <code>long v = Double.doubleToLongBits(doubleValue());<br>
419 * int hash = (int)(v^(v>>32))</code>.
421 * @return this Object's hash code
422 * @see #doubleToLongBits(double)
424 public int hashCode()
426 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.
437 * <p>Note that <code>d1.equals(d2)</code> is identical to
438 * <code>doubleToLongBits(d1.doubleValue()) ==
439 * doubleToLongBits(d2.doubleValue())</code>.
441 * @param obj the object to compare
442 * @return whether the objects are semantically equal
444 public boolean equals(Object obj)
446 if (! (obj instanceof Double))
449 double d = ((Double) obj).value;
451 // Avoid call to native method. However, some implementations, like gcj,
452 // are better off using floatToIntBits(value) == floatToIntBits(f).
453 // Check common case first, then check NaN and 0.
455 return (value != 0) || (1 / value == 1 / d);
456 return isNaN(value) && isNaN(d);
460 * Convert the double to the IEEE 754 floating-point "double format" bit
461 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
462 * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
463 * (masked by 0x000fffffffffffffL) are the mantissa. This function
464 * collapses all versions of NaN to 0x7ff8000000000000L. The result of this
465 * function can be used as the argument to
466 * <code>Double.longBitsToDouble(long)</code> to obtain the original
467 * <code>double</code> value.
469 * @param value the <code>double</code> to convert
470 * @return the bits of the <code>double</code>
471 * @see #longBitsToDouble(long)
473 public static long doubleToLongBits(double value)
476 return 0x7ff8000000000000L;
478 return 0; //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
484 * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
485 * (masked by 0x000fffffffffffffL) are the mantissa. This function
486 * leaves NaN alone, rather than collapsing to a canonical value. The
487 * result of this function can be used as the argument to
488 * <code>Double.longBitsToDouble(long)</code> to obtain the original
489 * <code>double</code> value.
491 * @param value the <code>double</code> to convert
492 * @return the bits of the <code>double</code>
493 * @see #longBitsToDouble(long)
495 public static long doubleToRawLongBits(double value)
497 return 0; //VMDouble.doubleToRawLongBits(value);
501 * Convert the argument in IEEE 754 floating-point "double format" bit
502 * layout to the corresponding float. Bit 63 (the most significant) is the
503 * sign bit, bits 62-52 (masked by 0x7ff0000000000000L) represent the
504 * exponent, and bits 51-0 (masked by 0x000fffffffffffffL) are the mantissa.
505 * This function leaves NaN alone, so that you can recover the bit pattern
506 * with <code>Double.doubleToRawLongBits(double)</code>.
508 * @param bits the bits to convert
509 * @return the <code>double</code> represented by the bits
510 * @see #doubleToLongBits(double)
511 * @see #doubleToRawLongBits(double)
513 public static double longBitsToDouble(long bits)
515 return 0.0; //VMDouble.longBitsToDouble(bits);
519 * Compare two Doubles numerically by comparing their <code>double</code>
520 * values. The result is positive if the first is greater, negative if the
521 * second is greater, and 0 if the two are equal. However, this special
522 * cases NaN and signed zero as follows: NaN is considered greater than
523 * all other doubles, including <code>POSITIVE_INFINITY</code>, and positive
524 * zero is considered greater than negative zero.
526 * @param d the Double to compare
527 * @return the comparison
530 public int compareTo(Double d)
532 return compare(value, d.value);
536 * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in
537 * other words this compares two doubles, special casing NaN and zero,
538 * without the overhead of objects.
540 * @param x the first double to compare
541 * @param y the second double to compare
542 * @return the comparison
545 public static int compare(double x, double y)
547 // handle the easy cases:
553 // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
554 long lx = doubleToRawLongBits(x);
555 long ly = doubleToRawLongBits(y);
561 return (y != y) ? 0 : 1;
566 return (lx < ly) ? -1 : 1;