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 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
68 private final double value;
71 * Create a <code>Double</code> from the primitive <code>double</code>
75 * the <code>double</code> argument
77 public Double(double value) {
82 * Create a <code>Double</code> from the specified <code>String</code>. This
83 * method calls <code>Double.parseDouble()</code>.
86 * the <code>String</code> to convert
87 * @throws NumberFormatException
88 * if <code>s</code> cannot be parsed as a <code>double</code>
89 * @throws NullPointerException
90 * if <code>s</code> is null
91 * @see #parseDouble(String)
93 public Double(String s) {
94 value = parseDouble(s);
98 * Convert the <code>double</code> to a <code>String</code>. Floating-point
99 * string representation is fairly complex: here is a rundown of the possible
100 * values. "<code>[-]</code>" indicates that a negative sign will be printed
101 * if the value (or exponent) is negative. "<code><number></code>" means
102 * a string of digits ('0' to '9'). "<code><digit></code>" means a
103 * single digit ('0' to '9').<br>
107 * <th>Value of Double</th>
108 * <th>String Representation</th>
112 * <td><code>[-]0.0</code></td>
115 * <td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
116 * <td><code>[-]number.number</code></td>
119 * <td>Other numeric value</td>
120 * <td><code>[-]<digit>.<number>
121 * E[-]<number></code></td>
124 * <td>[+-] infinity</td>
125 * <td><code>[-]Infinity</code></td>
129 * <td><code>NaN</code></td>
133 * Yes, negative zero <em>is</em> a possible value. Note that there is
134 * <em>always</em> a <code>.</code> and at least one digit printed after it:
135 * even if the number is 3, it will be printed as <code>3.0</code>. After the
136 * ".", all digits will be printed except trailing zeros. The result is
137 * rounded to the shortest decimal number which will parse back to the same
141 * To create other output formats, use {@link java.text.NumberFormat}.
143 * @XXX specify where we are not in accord with the spec.
146 * the <code>double</code> to convert
147 * @return the <code>String</code> representing the <code>double</code>
149 public static String toString(double d) {
150 return String.valueOf(d);
154 * Convert a double value to a hexadecimal string. This converts as follows:
156 * <li>A NaN value is converted to the string "NaN".
157 * <li>Positive infinity is converted to the string "Infinity".
158 * <li>Negative infinity is converted to the string "-Infinity".
159 * <li>For all other values, the first character of the result is '-' if the
160 * value is negative. This is followed by '0x1.' if the value is normal, and
161 * '0x0.' if the value is denormal. This is then followed by a (lower-case)
162 * hexadecimal representation of the mantissa, with leading zeros as required
163 * for denormal values. The next character is a 'p', and this is followed by a
164 * decimal representation of the unbiased exponent.
169 * @return the hexadecimal string representation
172 public static String toHexString(double d) {
174 * if (isNaN(d)) return "NaN"; if (isInfinite(d)) return d < 0 ? "-Infinity"
177 * long bits = doubleToLongBits(d); StringBuilder result = new
180 * if (bits < 0) result.append('-'); result.append("0x");
182 * final int mantissaBits = 52; final int exponentBits = 11; long mantMask =
183 * (1L << mantissaBits) - 1; long mantissa = bits & mantMask; long expMask =
184 * (1L << exponentBits) - 1; long exponent = (bits >>> mantissaBits) &
187 * result.append(exponent == 0 ? '0' : '1'); result.append('.');
188 * result.append(Long.toHexString(mantissa)); if (exponent == 0 && mantissa
189 * != 0) { // Treat denormal specially by inserting '0's to make // the
190 * length come out right. The constants here are // to account for things
191 * like the '0x'. int offset = 4 + ((bits < 0) ? 1 : 0); // The silly +3 is
192 * here to keep the code the same between // the Float and Double cases. In
193 * Float the value is // not a multiple of 4. int desiredLength = offset +
194 * (mantissaBits + 3) / 4; while (result.length() < desiredLength)
195 * result.insert(offset, '0'); } result.append('p'); if (exponent == 0 &&
196 * mantissa == 0) { // Zero, so do nothing special. } else { // Apply bias.
197 * boolean denormal = exponent == 0; exponent -= (1 << (exponentBits - 1)) -
198 * 1; // Handle denormal. if (denormal) ++exponent; }
200 * result.append(Long.toString(exponent)); return result.toString();
206 * Returns a <code>Double</code> object wrapping the value. In contrast to the
207 * <code>Double</code> constructor, this method may cache some values. It is
208 * used by boxing conversion.
212 * @return the <code>Double</code>
215 public static Double valueOf(double val) {
216 // We don't actually cache, but we could.
217 return new Double(val);
221 * Create a new <code>Double</code> object using the <code>String</code>.
224 * the <code>String</code> to convert
225 * @return the new <code>Double</code>
226 * @throws NumberFormatException
227 * if <code>s</code> cannot be parsed as a <code>double</code>
228 * @throws NullPointerException
229 * 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>
241 * <em>DecodableString</em>:
242 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
243 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
244 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
245 * [ <code>f</code> | <code>F</code> | <code>d</code>
246 * | <code>D</code>] )
247 * <em>FloatingPoint</em>:
248 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
249 * [ <em>Exponent</em> ] )
250 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
252 * ( ( <code>e</code> | <code>E</code> )
253 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
254 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
258 * NaN and infinity are special cases, to allow parsing of the output of
259 * toString. Otherwise, the result is determined by calculating
260 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding to
261 * the nearest double. Remember that many numbers cannot be precisely
262 * represented in floating point. In case of overflow, infinity is used, and
263 * in case of underflow, signed zero is used. Unlike Integer.parseInt, this
264 * does not accept Unicode digits outside the ASCII range.
267 * If an unexpected character is found in the <code>String</code>, a
268 * <code>NumberFormatException</code> will be thrown. Leading and trailing
269 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces internal
270 * to the actual number are not allowed.
273 * To parse numbers according to another format, consider using
274 * {@link java.text.NumberFormat}.
276 * @XXX specify where/how we are not in accord with the spec.
279 * the <code>String</code> to convert
280 * @return the <code>double</code> value of <code>s</code>
281 * @throws NumberFormatException
282 * if <code>s</code> cannot be parsed as a <code>double</code>
283 * @throws NullPointerException
284 * if <code>s</code> is null
287 * @see #POSITIVE_INFINITY
288 * @see #NEGATIVE_INFINITY
291 public static double parseDouble(String str) {
292 return nativeparsedouble(str);
295 public static native double nativeparsedouble(String str);
297 public static native double nativeparsedouble(int start, int length, byte[] str);
300 * Return <code>true</code> if the <code>double</code> has the same value as
301 * <code>NaN</code>, otherwise return <code>false</code>.
304 * the <code>double</code> to compare
305 * @return whether the argument is <code>NaN</code>.
307 public static boolean isNaN(double v) {
308 // This works since NaN != NaN is the only reflexive inequality
309 // comparison which returns true.
314 * Return <code>true</code> if the <code>double</code> has a value equal to
315 * either <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
316 * otherwise return <code>false</code>.
319 * the <code>double</code> to compare
320 * @return whether the argument is (-/+) infinity.
322 public static boolean isInfinite(double v) {
327 * Return <code>true</code> if the value of this <code>Double</code> is the
328 * same as <code>NaN</code>, otherwise return <code>false</code>.
330 * @return whether this <code>Double</code> is <code>NaN</code>
332 public boolean isNaN() {
337 * Return <code>true</code> if the value of this <code>Double</code> is the
338 * same as <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
339 * otherwise return <code>false</code>.
341 * @return whether this <code>Double</code> is (-/+) infinity
343 public boolean isInfinite() {
344 return isInfinite(value);
348 * Convert the <code>double</code> value of this <code>Double</code> to a
349 * <code>String</code>. This method calls <code>Double.toString(double)</code>
350 * to do its dirty work.
352 * @return the <code>String</code> representation
353 * @see #toString(double)
355 public String toString() {
356 return toString(value);
360 * Return the value of this <code>Double</code> as a <code>byte</code>.
362 * @return the byte value
365 public byte byteValue() {
370 * Return the value of this <code>Double</code> as a <code>short</code>.
372 * @return the short value
375 public short shortValue() {
376 return (short) value;
380 * Return the value of this <code>Double</code> as an <code>int</code>.
382 * @return the int value
384 public int intValue() {
389 * Return the value of this <code>Double</code> as a <code>long</code>.
391 * @return the long value
393 public long longValue() {
398 * Return the value of this <code>Double</code> as a <code>float</code>.
400 * @return the float value
402 public float floatValue() {
403 return (float) value;
407 * Return the value of this <code>Double</code>.
409 * @return the double value
411 public double doubleValue() {
416 * Return a hashcode representing this Object. <code>Double</code>'s hash code
417 * 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() {
425 long v = doubleToLongBits(value);
426 return (int) (v ^ (v >>> 32));
430 * Returns <code>true</code> if <code>obj</code> is an instance of
431 * <code>Double</code> and represents the same double value. Unlike comparing
432 * two doubles with <code>==</code>, this treats two instances of
433 * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
434 * <code>-0.0</code> as unequal.
437 * Note that <code>d1.equals(d2)</code> is identical to
438 * <code>doubleToLongBits(d1.doubleValue()) ==
439 * doubleToLongBits(d2.doubleValue())</code>.
442 * the object to compare
443 * @return whether the objects are semantically equal
445 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 (masked
462 * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
463 * 0x000fffffffffffffL) are the mantissa. This function collapses all versions
464 * of NaN to 0x7ff8000000000000L. The result of this function can be used as
465 * the argument to <code>Double.longBitsToDouble(long)</code> to obtain the
466 * original <code>double</code> value.
469 * 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) {
475 return 0x7ff8000000000000L;
477 return /* VMDouble. */doubleToRawLongBits(value);
481 * Convert the double to the IEEE 754 floating-point "double format" bit
482 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52 (masked
483 * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
484 * 0x000fffffffffffffL) are the mantissa. This function leaves NaN alone,
485 * rather than collapsing to a canonical value. The result of this function
486 * can be used as the argument to <code>Double.longBitsToDouble(long)</code>
487 * to obtain the original <code>double</code> value.
490 * the <code>double</code> to convert
491 * @return the bits of the <code>double</code>
492 * @see #longBitsToDouble(long)
495 * public static long doubleToRawLongBits(double value) { return
496 * VMDouble.doubleToRawLongBits(value); }
498 public static native long doubleToRawLongBits(double value);
501 * Convert the argument in IEEE 754 floating-point "double format" bit layout
502 * to the corresponding float. Bit 63 (the most significant) is the sign bit,
503 * bits 62-52 (masked by 0x7ff0000000000000L) represent the exponent, and bits
504 * 51-0 (masked by 0x000fffffffffffffL) are the mantissa. This function leaves
505 * NaN alone, so that you can recover the bit pattern with
506 * <code>Double.doubleToRawLongBits(double)</code>.
509 * the bits to convert
510 * @return the <code>double</code> represented by the bits
511 * @see #doubleToLongBits(double)
512 * @see #doubleToRawLongBits(double)
515 * public static double longBitsToDouble(long bits) { return
516 * VMDouble.longBitsToDouble(bits); }
518 public static native double longBitsToDouble(long bits);
521 * Compare two Doubles numerically by comparing their <code>double</code>
522 * values. The result is positive if the first is greater, negative if the
523 * second is greater, and 0 if the two are equal. However, this special cases
524 * NaN and signed zero as follows: NaN is considered greater than all other
525 * doubles, including <code>POSITIVE_INFINITY</code>, and positive zero is
526 * considered greater than negative zero.
529 * the Double to compare
530 * @return the comparison
533 public int compareTo(Double d) {
534 return compare(value, d.value);
538 * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in other
539 * words this compares two doubles, special casing NaN and zero, without the
540 * overhead of objects.
543 * the first double to compare
545 * the second double to compare
546 * @return the comparison
549 public static int compare(double x, double y) {
550 // handle the easy cases:
556 // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
557 long lx = doubleToRawLongBits(x);
558 long ly = doubleToRawLongBits(y);
564 return (y != y) ? 0 : 1;
569 return (lx < ly) ? -1 : 1;