1 /* 2 * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import sun.misc.FloatingDecimal; 29 import sun.misc.FpUtils; 30 import sun.misc.DoubleConsts; 31 32 /** 33 * The {@code Double} class wraps a value of the primitive type 34 * {@code double} in an object. An object of type 35 * {@code Double} contains a single field whose type is 36 * {@code double}. 37 * 38 * <p>In addition, this class provides several methods for converting a 39 * {@code double} to a {@code String} and a 40 * {@code String} to a {@code double}, as well as other 41 * constants and methods useful when dealing with a 42 * {@code double}. 43 * 44 * @author Lee Boynton 45 * @author Arthur van Hoff 46 * @author Joseph D. Darcy 47 * @since JDK1.0 48 */ 49 public final class Double extends Number implements Comparable<Double> { 50 /** 51 * A constant holding the positive infinity of type 52 * {@code double}. It is equal to the value returned by 53 * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. 54 */ 55 public static final double POSITIVE_INFINITY = 1.0 / 0.0; 56 57 /** 58 * A constant holding the negative infinity of type 59 * {@code double}. It is equal to the value returned by 60 * {@code Double.longBitsToDouble(0xfff0000000000000L)}. 61 */ 62 public static final double NEGATIVE_INFINITY = -1.0 / 0.0; 63 64 /** 65 * A constant holding a Not-a-Number (NaN) value of type 66 * {@code double}. It is equivalent to the value returned by 67 * {@code Double.longBitsToDouble(0x7ff8000000000000L)}. 68 */ 69 public static final double NaN = 0.0d / 0.0; 70 71 /** 72 * A constant holding the largest positive finite value of type 73 * {@code double}, 74 * (2-2<sup>-52</sup>)·2<sup>1023</sup>. It is equal to 75 * the hexadecimal floating-point literal 76 * {@code 0x1.fffffffffffffP+1023} and also equal to 77 * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}. 78 */ 79 public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308 80 81 /** 82 * A constant holding the smallest positive normal value of type 83 * {@code double}, 2<sup>-1022</sup>. It is equal to the 84 * hexadecimal floating-point literal {@code 0x1.0p-1022} and also 85 * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}. 86 * 87 * @since 1.6 88 */ 89 public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 90 91 /** 92 * A constant holding the smallest positive nonzero value of type 93 * {@code double}, 2<sup>-1074</sup>. It is equal to the 94 * hexadecimal floating-point literal 95 * {@code 0x0.0000000000001P-1022} and also equal to 96 * {@code Double.longBitsToDouble(0x1L)}. 97 */ 98 public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324 99 100 /** 101 * Maximum exponent a finite {@code double} variable may have. 102 * It is equal to the value returned by 103 * {@code Math.getExponent(Double.MAX_VALUE)}. 104 * 105 * @since 1.6 106 */ 107 public static final int MAX_EXPONENT = 1023; 108 109 /** 110 * Minimum exponent a normalized {@code double} variable may 111 * have. It is equal to the value returned by 112 * {@code Math.getExponent(Double.MIN_NORMAL)}. 113 * 114 * @since 1.6 115 */ 116 public static final int MIN_EXPONENT = -1022; 117 118 /** 119 * The number of bits used to represent a {@code double} value. 120 * 121 * @since 1.5 122 */ 123 public static final int SIZE = 64; 124 125 /** 126 * The number of bytes used to represent a {@code double} value. 127 * 128 * @since 1.8 129 */ 130 public static final int BYTES = SIZE / Byte.SIZE; 131 132 /** 133 * The {@code Class} instance representing the primitive type 134 * {@code double}. 135 * 136 * @since JDK1.1 137 */ 138 @SuppressWarnings("unchecked") 139 public static final Class<Double> TYPE = (Class<Double>) Class.getPrimitiveClass("double"); 140 141 /** 142 * Returns a string representation of the {@code double} 143 * argument. All characters mentioned below are ASCII characters. 144 * <ul> 145 * <li>If the argument is NaN, the result is the string 146 * "{@code NaN}". 147 * <li>Otherwise, the result is a string that represents the sign and 148 * magnitude (absolute value) of the argument. If the sign is negative, 149 * the first character of the result is '{@code -}' 150 * ({@code '\u005Cu002D'}); if the sign is positive, no sign character 151 * appears in the result. As for the magnitude <i>m</i>: 152 * <ul> 153 * <li>If <i>m</i> is infinity, it is represented by the characters 154 * {@code "Infinity"}; thus, positive infinity produces the result 155 * {@code "Infinity"} and negative infinity produces the result 156 * {@code "-Infinity"}. 157 * 158 * <li>If <i>m</i> is zero, it is represented by the characters 159 * {@code "0.0"}; thus, negative zero produces the result 160 * {@code "-0.0"} and positive zero produces the result 161 * {@code "0.0"}. 162 * 163 * <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less 164 * than 10<sup>7</sup>, then it is represented as the integer part of 165 * <i>m</i>, in decimal form with no leading zeroes, followed by 166 * '{@code .}' ({@code '\u005Cu002E'}), followed by one or 167 * more decimal digits representing the fractional part of <i>m</i>. 168 * 169 * <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or 170 * equal to 10<sup>7</sup>, then it is represented in so-called 171 * "computerized scientific notation." Let <i>n</i> be the unique 172 * integer such that 10<sup><i>n</i></sup> ≤ <i>m</i> {@literal <} 173 * 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the 174 * mathematically exact quotient of <i>m</i> and 175 * 10<sup><i>n</i></sup> so that 1 ≤ <i>a</i> {@literal <} 10. The 176 * magnitude is then represented as the integer part of <i>a</i>, 177 * as a single decimal digit, followed by '{@code .}' 178 * ({@code '\u005Cu002E'}), followed by decimal digits 179 * representing the fractional part of <i>a</i>, followed by the 180 * letter '{@code E}' ({@code '\u005Cu0045'}), followed 181 * by a representation of <i>n</i> as a decimal integer, as 182 * produced by the method {@link Integer#toString(int)}. 183 * </ul> 184 * </ul> 185 * How many digits must be printed for the fractional part of 186 * <i>m</i> or <i>a</i>? There must be at least one digit to represent 187 * the fractional part, and beyond that as many, but only as many, more 188 * digits as are needed to uniquely distinguish the argument value from 189 * adjacent values of type {@code double}. That is, suppose that 190 * <i>x</i> is the exact mathematical value represented by the decimal 191 * representation produced by this method for a finite nonzero argument 192 * <i>d</i>. Then <i>d</i> must be the {@code double} value nearest 193 * to <i>x</i>; or if two {@code double} values are equally close 194 * to <i>x</i>, then <i>d</i> must be one of them and the least 195 * significant bit of the significand of <i>d</i> must be {@code 0}. 196 * 197 * <p>To create localized string representations of a floating-point 198 * value, use subclasses of {@link java.text.NumberFormat}. 199 * 200 * @param d the {@code double} to be converted. 201 * @return a string representation of the argument. 202 */ 203 public static String toString(double d) { 204 return new FloatingDecimal(d).toJavaFormatString(); 205 } 206 207 /** 208 * Returns a hexadecimal string representation of the 209 * {@code double} argument. All characters mentioned below 210 * are ASCII characters. 211 * 212 * <ul> 213 * <li>If the argument is NaN, the result is the string 214 * "{@code NaN}". 215 * <li>Otherwise, the result is a string that represents the sign 216 * and magnitude of the argument. If the sign is negative, the 217 * first character of the result is '{@code -}' 218 * ({@code '\u005Cu002D'}); if the sign is positive, no sign 219 * character appears in the result. As for the magnitude <i>m</i>: 220 * 221 * <ul> 222 * <li>If <i>m</i> is infinity, it is represented by the string 223 * {@code "Infinity"}; thus, positive infinity produces the 224 * result {@code "Infinity"} and negative infinity produces 225 * the result {@code "-Infinity"}. 226 * 227 * <li>If <i>m</i> is zero, it is represented by the string 228 * {@code "0x0.0p0"}; thus, negative zero produces the result 229 * {@code "-0x0.0p0"} and positive zero produces the result 230 * {@code "0x0.0p0"}. 231 * 232 * <li>If <i>m</i> is a {@code double} value with a 233 * normalized representation, substrings are used to represent the 234 * significand and exponent fields. The significand is 235 * represented by the characters {@code "0x1."} 236 * followed by a lowercase hexadecimal representation of the rest 237 * of the significand as a fraction. Trailing zeros in the 238 * hexadecimal representation are removed unless all the digits 239 * are zero, in which case a single zero is used. Next, the 240 * exponent is represented by {@code "p"} followed 241 * by a decimal string of the unbiased exponent as if produced by 242 * a call to {@link Integer#toString(int) Integer.toString} on the 243 * exponent value. 244 * 245 * <li>If <i>m</i> is a {@code double} value with a subnormal 246 * representation, the significand is represented by the 247 * characters {@code "0x0."} followed by a 248 * hexadecimal representation of the rest of the significand as a 249 * fraction. Trailing zeros in the hexadecimal representation are 250 * removed. Next, the exponent is represented by 251 * {@code "p-1022"}. Note that there must be at 252 * least one nonzero digit in a subnormal significand. 253 * 254 * </ul> 255 * 256 * </ul> 257 * 258 * <table border> 259 * <caption><h3>Examples</h3></caption> 260 * <tr><th>Floating-point Value</th><th>Hexadecimal String</th> 261 * <tr><td>{@code 1.0}</td> <td>{@code 0x1.0p0}</td> 262 * <tr><td>{@code -1.0}</td> <td>{@code -0x1.0p0}</td> 263 * <tr><td>{@code 2.0}</td> <td>{@code 0x1.0p1}</td> 264 * <tr><td>{@code 3.0}</td> <td>{@code 0x1.8p1}</td> 265 * <tr><td>{@code 0.5}</td> <td>{@code 0x1.0p-1}</td> 266 * <tr><td>{@code 0.25}</td> <td>{@code 0x1.0p-2}</td> 267 * <tr><td>{@code Double.MAX_VALUE}</td> 268 * <td>{@code 0x1.fffffffffffffp1023}</td> 269 * <tr><td>{@code Minimum Normal Value}</td> 270 * <td>{@code 0x1.0p-1022}</td> 271 * <tr><td>{@code Maximum Subnormal Value}</td> 272 * <td>{@code 0x0.fffffffffffffp-1022}</td> 273 * <tr><td>{@code Double.MIN_VALUE}</td> 274 * <td>{@code 0x0.0000000000001p-1022}</td> 275 * </table> 276 * @param d the {@code double} to be converted. 277 * @return a hex string representation of the argument. 278 * @since 1.5 279 * @author Joseph D. Darcy 280 */ 281 public static String toHexString(double d) { 282 /* 283 * Modeled after the "a" conversion specifier in C99, section 284 * 7.19.6.1; however, the output of this method is more 285 * tightly specified. 286 */ 287 if (!isFinite(d) ) 288 // For infinity and NaN, use the decimal output. 289 return Double.toString(d); 290 else { 291 // Initialized to maximum size of output. 292 StringBuffer answer = new StringBuffer(24); 293 294 if (Math.copySign(1.0, d) == -1.0) // value is negative, 295 answer.append("-"); // so append sign info 296 297 answer.append("0x"); 298 299 d = Math.abs(d); 300 301 if(d == 0.0) { 302 answer.append("0.0p0"); 303 } 304 else { 305 boolean subnormal = (d < DoubleConsts.MIN_NORMAL); 306 307 // Isolate significand bits and OR in a high-order bit 308 // so that the string representation has a known 309 // length. 310 long signifBits = (Double.doubleToLongBits(d) 311 & DoubleConsts.SIGNIF_BIT_MASK) | 312 0x1000000000000000L; 313 314 // Subnormal values have a 0 implicit bit; normal 315 // values have a 1 implicit bit. 316 answer.append(subnormal ? "0." : "1."); 317 318 // Isolate the low-order 13 digits of the hex 319 // representation. If all the digits are zero, 320 // replace with a single 0; otherwise, remove all 321 // trailing zeros. 322 String signif = Long.toHexString(signifBits).substring(3,16); 323 answer.append(signif.equals("0000000000000") ? // 13 zeros 324 "0": 325 signif.replaceFirst("0{1,12}$", "")); 326 327 // If the value is subnormal, use the E_min exponent 328 // value for double; otherwise, extract and report d's 329 // exponent (the representation of a subnormal uses 330 // E_min -1). 331 answer.append("p" + (subnormal ? 332 DoubleConsts.MIN_EXPONENT: 333 Math.getExponent(d) )); 334 } 335 return answer.toString(); 336 } 337 } 338 339 /** 340 * Returns a {@code Double} object holding the 341 * {@code double} value represented by the argument string 342 * {@code s}. 343 * 344 * <p>If {@code s} is {@code null}, then a 345 * {@code NullPointerException} is thrown. 346 * 347 * <p>Leading and trailing whitespace characters in {@code s} 348 * are ignored. Whitespace is removed as if by the {@link 349 * String#trim} method; that is, both ASCII space and control 350 * characters are removed. The rest of {@code s} should 351 * constitute a <i>FloatValue</i> as described by the lexical 352 * syntax rules: 353 * 354 * <blockquote> 355 * <dl> 356 * <dt><i>FloatValue:</i> 357 * <dd><i>Sign<sub>opt</sub></i> {@code NaN} 358 * <dd><i>Sign<sub>opt</sub></i> {@code Infinity} 359 * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i> 360 * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i> 361 * <dd><i>SignedInteger</i> 362 * </dl> 363 * 364 * <p> 365 * 366 * <dl> 367 * <dt><i>HexFloatingPointLiteral</i>: 368 * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i> 369 * </dl> 370 * 371 * <p> 372 * 373 * <dl> 374 * <dt><i>HexSignificand:</i> 375 * <dd><i>HexNumeral</i> 376 * <dd><i>HexNumeral</i> {@code .} 377 * <dd>{@code 0x} <i>HexDigits<sub>opt</sub> 378 * </i>{@code .}<i> HexDigits</i> 379 * <dd>{@code 0X}<i> HexDigits<sub>opt</sub> 380 * </i>{@code .} <i>HexDigits</i> 381 * </dl> 382 * 383 * <p> 384 * 385 * <dl> 386 * <dt><i>BinaryExponent:</i> 387 * <dd><i>BinaryExponentIndicator SignedInteger</i> 388 * </dl> 389 * 390 * <p> 391 * 392 * <dl> 393 * <dt><i>BinaryExponentIndicator:</i> 394 * <dd>{@code p} 395 * <dd>{@code P} 396 * </dl> 397 * 398 * </blockquote> 399 * 400 * where <i>Sign</i>, <i>FloatingPointLiteral</i>, 401 * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and 402 * <i>FloatTypeSuffix</i> are as defined in the lexical structure 403 * sections of 404 * <cite>The Java™ Language Specification</cite>, 405 * except that underscores are not accepted between digits. 406 * If {@code s} does not have the form of 407 * a <i>FloatValue</i>, then a {@code NumberFormatException} 408 * is thrown. Otherwise, {@code s} is regarded as 409 * representing an exact decimal value in the usual 410 * "computerized scientific notation" or as an exact 411 * hexadecimal value; this exact numerical value is then 412 * conceptually converted to an "infinitely precise" 413 * binary value that is then rounded to type {@code double} 414 * by the usual round-to-nearest rule of IEEE 754 floating-point 415 * arithmetic, which includes preserving the sign of a zero 416 * value. 417 * 418 * Note that the round-to-nearest rule also implies overflow and 419 * underflow behaviour; if the exact value of {@code s} is large 420 * enough in magnitude (greater than or equal to ({@link 421 * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2), 422 * rounding to {@code double} will result in an infinity and if the 423 * exact value of {@code s} is small enough in magnitude (less 424 * than or equal to {@link #MIN_VALUE}/2), rounding to float will 425 * result in a zero. 426 * 427 * Finally, after rounding a {@code Double} object representing 428 * this {@code double} value is returned. 429 * 430 * <p> To interpret localized string representations of a 431 * floating-point value, use subclasses of {@link 432 * java.text.NumberFormat}. 433 * 434 * <p>Note that trailing format specifiers, specifiers that 435 * determine the type of a floating-point literal 436 * ({@code 1.0f} is a {@code float} value; 437 * {@code 1.0d} is a {@code double} value), do 438 * <em>not</em> influence the results of this method. In other 439 * words, the numerical value of the input string is converted 440 * directly to the target floating-point type. The two-step 441 * sequence of conversions, string to {@code float} followed 442 * by {@code float} to {@code double}, is <em>not</em> 443 * equivalent to converting a string directly to 444 * {@code double}. For example, the {@code float} 445 * literal {@code 0.1f} is equal to the {@code double} 446 * value {@code 0.10000000149011612}; the {@code float} 447 * literal {@code 0.1f} represents a different numerical 448 * value than the {@code double} literal 449 * {@code 0.1}. (The numerical value 0.1 cannot be exactly 450 * represented in a binary floating-point number.) 451 * 452 * <p>To avoid calling this method on an invalid string and having 453 * a {@code NumberFormatException} be thrown, the regular 454 * expression below can be used to screen the input string: 455 * 456 * <code> 457 * <pre> 458 * final String Digits = "(\\p{Digit}+)"; 459 * final String HexDigits = "(\\p{XDigit}+)"; 460 * // an exponent is 'e' or 'E' followed by an optionally 461 * // signed decimal integer. 462 * final String Exp = "[eE][+-]?"+Digits; 463 * final String fpRegex = 464 * ("[\\x00-\\x20]*"+ // Optional leading "whitespace" 465 * "[+-]?(" + // Optional sign character 466 * "NaN|" + // "NaN" string 467 * "Infinity|" + // "Infinity" string 468 * 469 * // A decimal floating-point string representing a finite positive 470 * // number without a leading sign has at most five basic pieces: 471 * // Digits . Digits ExponentPart FloatTypeSuffix 472 * // 473 * // Since this method allows integer-only strings as input 474 * // in addition to strings of floating-point literals, the 475 * // two sub-patterns below are simplifications of the grammar 476 * // productions from section 3.10.2 of 477 * // <cite>The Java™ Language Specification</cite>. 478 * 479 * // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt 480 * "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ 481 * 482 * // . Digits ExponentPart_opt FloatTypeSuffix_opt 483 * "(\\.("+Digits+")("+Exp+")?)|"+ 484 * 485 * // Hexadecimal strings 486 * "((" + 487 * // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt 488 * "(0[xX]" + HexDigits + "(\\.)?)|" + 489 * 490 * // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt 491 * "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + 492 * 493 * ")[pP][+-]?" + Digits + "))" + 494 * "[fFdD]?))" + 495 * "[\\x00-\\x20]*");// Optional trailing "whitespace" 496 * 497 * if (Pattern.matches(fpRegex, myString)) 498 * Double.valueOf(myString); // Will not throw NumberFormatException 499 * else { 500 * // Perform suitable alternative action 501 * } 502 * </pre> 503 * </code> 504 * 505 * @param s the string to be parsed. 506 * @return a {@code Double} object holding the value 507 * represented by the {@code String} argument. 508 * @throws NumberFormatException if the string does not contain a 509 * parsable number. 510 */ 511 public static Double valueOf(String s) throws NumberFormatException { 512 return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue()); 513 } 514 515 /** 516 * Returns a {@code Double} instance representing the specified 517 * {@code double} value. 518 * If a new {@code Double} instance is not required, this method 519 * should generally be used in preference to the constructor 520 * {@link #Double(double)}, as this method is likely to yield 521 * significantly better space and time performance by caching 522 * frequently requested values. 523 * 524 * @param d a double value. 525 * @return a {@code Double} instance representing {@code d}. 526 * @since 1.5 527 */ 528 public static Double valueOf(double d) { 529 return new Double(d); 530 } 531 532 /** 533 * Returns a new {@code double} initialized to the value 534 * represented by the specified {@code String}, as performed 535 * by the {@code valueOf} method of class 536 * {@code Double}. 537 * 538 * @param s the string to be parsed. 539 * @return the {@code double} value represented by the string 540 * argument. 541 * @throws NullPointerException if the string is null 542 * @throws NumberFormatException if the string does not contain 543 * a parsable {@code double}. 544 * @see java.lang.Double#valueOf(String) 545 * @since 1.2 546 */ 547 public static double parseDouble(String s) throws NumberFormatException { 548 return FloatingDecimal.readJavaFormatString(s).doubleValue(); 549 } 550 551 /** 552 * Returns {@code true} if the specified number is a 553 * Not-a-Number (NaN) value, {@code false} otherwise. 554 * 555 * @param v the value to be tested. 556 * @return {@code true} if the value of the argument is NaN; 557 * {@code false} otherwise. 558 */ 559 public static boolean isNaN(double v) { 560 return (v != v); 561 } 562 563 /** 564 * Returns {@code true} if the specified number is infinitely 565 * large in magnitude, {@code false} otherwise. 566 * 567 * @param v the value to be tested. 568 * @return {@code true} if the value of the argument is positive 569 * infinity or negative infinity; {@code false} otherwise. 570 */ 571 public static boolean isInfinite(double v) { 572 return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); 573 } 574 575 /** 576 * Returns {@code true} if the argument is a finite floating-point 577 * value; returns {@code false} otherwise (for NaN and infinity 578 * arguments). 579 * 580 * @param d the {@code double} value to be tested 581 * @return {@code true} if the argument is a finite 582 * floating-point value, {@code false} otherwise. 583 * @since 1.8 584 */ 585 public static boolean isFinite(double d) { 586 return Math.abs(d) <= DoubleConsts.MAX_VALUE; 587 } 588 589 /** 590 * The value of the Double. 591 * 592 * @serial 593 */ 594 private final double value; 595 596 /** 597 * Constructs a newly allocated {@code Double} object that 598 * represents the primitive {@code double} argument. 599 * 600 * @param value the value to be represented by the {@code Double}. 601 */ 602 public Double(double value) { 603 this.value = value; 604 } 605 606 /** 607 * Constructs a newly allocated {@code Double} object that 608 * represents the floating-point value of type {@code double} 609 * represented by the string. The string is converted to a 610 * {@code double} value as if by the {@code valueOf} method. 611 * 612 * @param s a string to be converted to a {@code Double}. 613 * @throws NumberFormatException if the string does not contain a 614 * parsable number. 615 * @see java.lang.Double#valueOf(java.lang.String) 616 */ 617 public Double(String s) throws NumberFormatException { 618 value = parseDouble(s); 619 } 620 621 /** 622 * Returns {@code true} if this {@code Double} value is 623 * a Not-a-Number (NaN), {@code false} otherwise. 624 * 625 * @return {@code true} if the value represented by this object is 626 * NaN; {@code false} otherwise. 627 */ 628 public boolean isNaN() { 629 return isNaN(value); 630 } 631 632 /** 633 * Returns {@code true} if this {@code Double} value is 634 * infinitely large in magnitude, {@code false} otherwise. 635 * 636 * @return {@code true} if the value represented by this object is 637 * positive infinity or negative infinity; 638 * {@code false} otherwise. 639 */ 640 public boolean isInfinite() { 641 return isInfinite(value); 642 } 643 644 /** 645 * Returns a string representation of this {@code Double} object. 646 * The primitive {@code double} value represented by this 647 * object is converted to a string exactly as if by the method 648 * {@code toString} of one argument. 649 * 650 * @return a {@code String} representation of this object. 651 * @see java.lang.Double#toString(double) 652 */ 653 public String toString() { 654 return toString(value); 655 } 656 657 /** 658 * Returns the value of this {@code Double} as a {@code byte} 659 * after a narrowing primitive conversion. 660 * 661 * @return the {@code double} value represented by this object 662 * converted to type {@code byte} 663 * @jls 5.1.3 Narrowing Primitive Conversions 664 * @since JDK1.1 665 */ 666 public byte byteValue() { 667 return (byte)value; 668 } 669 670 /** 671 * Returns the value of this {@code Double} as a {@code short} 672 * after a narrowing primitive conversion. 673 * 674 * @return the {@code double} value represented by this object 675 * converted to type {@code short} 676 * @jls 5.1.3 Narrowing Primitive Conversions 677 * @since JDK1.1 678 */ 679 public short shortValue() { 680 return (short)value; 681 } 682 683 /** 684 * Returns the value of this {@code Double} as an {@code int} 685 * after a narrowing primitive conversion. 686 * @jls 5.1.3 Narrowing Primitive Conversions 687 * 688 * @return the {@code double} value represented by this object 689 * converted to type {@code int} 690 */ 691 public int intValue() { 692 return (int)value; 693 } 694 695 /** 696 * Returns the value of this {@code Double} as a {@code long} 697 * after a narrowing primitive conversion. 698 * 699 * @return the {@code double} value represented by this object 700 * converted to type {@code long} 701 * @jls 5.1.3 Narrowing Primitive Conversions 702 */ 703 public long longValue() { 704 return (long)value; 705 } 706 707 /** 708 * Returns the value of this {@code Double} as a {@code float} 709 * after a narrowing primitive conversion. 710 * 711 * @return the {@code double} value represented by this object 712 * converted to type {@code float} 713 * @jls 5.1.3 Narrowing Primitive Conversions 714 * @since JDK1.0 715 */ 716 public float floatValue() { 717 return (float)value; 718 } 719 720 /** 721 * Returns the {@code double} value of this {@code Double} object. 722 * 723 * @return the {@code double} value represented by this object 724 */ 725 public double doubleValue() { 726 return value; 727 } 728 729 /** 730 * Returns a hash code for this {@code Double} object. The 731 * result is the exclusive OR of the two halves of the 732 * {@code long} integer bit representation, exactly as 733 * produced by the method {@link #doubleToLongBits(double)}, of 734 * the primitive {@code double} value represented by this 735 * {@code Double} object. That is, the hash code is the value 736 * of the expression: 737 * 738 * <blockquote> 739 * {@code (int)(v^(v>>>32))} 740 * </blockquote> 741 * 742 * where {@code v} is defined by: 743 * 744 * <blockquote> 745 * {@code long v = Double.doubleToLongBits(this.doubleValue());} 746 * </blockquote> 747 * 748 * @return a {@code hash code} value for this object. 749 */ 750 public int hashCode() { 751 long bits = doubleToLongBits(value); 752 return (int)(bits ^ (bits >>> 32)); 753 } 754 755 /** 756 * Compares this object against the specified object. The result 757 * is {@code true} if and only if the argument is not 758 * {@code null} and is a {@code Double} object that 759 * represents a {@code double} that has the same value as the 760 * {@code double} represented by this object. For this 761 * purpose, two {@code double} values are considered to be 762 * the same if and only if the method {@link 763 * #doubleToLongBits(double)} returns the identical 764 * {@code long} value when applied to each. 765 * 766 * <p>Note that in most cases, for two instances of class 767 * {@code Double}, {@code d1} and {@code d2}, the 768 * value of {@code d1.equals(d2)} is {@code true} if and 769 * only if 770 * 771 * <blockquote> 772 * {@code d1.doubleValue() == d2.doubleValue()} 773 * </blockquote> 774 * 775 * <p>also has the value {@code true}. However, there are two 776 * exceptions: 777 * <ul> 778 * <li>If {@code d1} and {@code d2} both represent 779 * {@code Double.NaN}, then the {@code equals} method 780 * returns {@code true}, even though 781 * {@code Double.NaN==Double.NaN} has the value 782 * {@code false}. 783 * <li>If {@code d1} represents {@code +0.0} while 784 * {@code d2} represents {@code -0.0}, or vice versa, 785 * the {@code equal} test has the value {@code false}, 786 * even though {@code +0.0==-0.0} has the value {@code true}. 787 * </ul> 788 * This definition allows hash tables to operate properly. 789 * @param obj the object to compare with. 790 * @return {@code true} if the objects are the same; 791 * {@code false} otherwise. 792 * @see java.lang.Double#doubleToLongBits(double) 793 */ 794 public boolean equals(Object obj) { 795 return (obj instanceof Double) 796 && (doubleToLongBits(((Double)obj).value) == 797 doubleToLongBits(value)); 798 } 799 800 /** 801 * Returns a representation of the specified floating-point value 802 * according to the IEEE 754 floating-point "double 803 * format" bit layout. 804 * 805 * <p>Bit 63 (the bit that is selected by the mask 806 * {@code 0x8000000000000000L}) represents the sign of the 807 * floating-point number. Bits 808 * 62-52 (the bits that are selected by the mask 809 * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 810 * (the bits that are selected by the mask 811 * {@code 0x000fffffffffffffL}) represent the significand 812 * (sometimes called the mantissa) of the floating-point number. 813 * 814 * <p>If the argument is positive infinity, the result is 815 * {@code 0x7ff0000000000000L}. 816 * 817 * <p>If the argument is negative infinity, the result is 818 * {@code 0xfff0000000000000L}. 819 * 820 * <p>If the argument is NaN, the result is 821 * {@code 0x7ff8000000000000L}. 822 * 823 * <p>In all cases, the result is a {@code long} integer that, when 824 * given to the {@link #longBitsToDouble(long)} method, will produce a 825 * floating-point value the same as the argument to 826 * {@code doubleToLongBits} (except all NaN values are 827 * collapsed to a single "canonical" NaN value). 828 * 829 * @param value a {@code double} precision floating-point number. 830 * @return the bits that represent the floating-point number. 831 */ 832 public static long doubleToLongBits(double value) { 833 long result = doubleToRawLongBits(value); 834 // Check for NaN based on values of bit fields, maximum 835 // exponent and nonzero significand. 836 if ( ((result & DoubleConsts.EXP_BIT_MASK) == 837 DoubleConsts.EXP_BIT_MASK) && 838 (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L) 839 result = 0x7ff8000000000000L; 840 return result; 841 } 842 843 /** 844 * Returns a representation of the specified floating-point value 845 * according to the IEEE 754 floating-point "double 846 * format" bit layout, preserving Not-a-Number (NaN) values. 847 * 848 * <p>Bit 63 (the bit that is selected by the mask 849 * {@code 0x8000000000000000L}) represents the sign of the 850 * floating-point number. Bits 851 * 62-52 (the bits that are selected by the mask 852 * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 853 * (the bits that are selected by the mask 854 * {@code 0x000fffffffffffffL}) represent the significand 855 * (sometimes called the mantissa) of the floating-point number. 856 * 857 * <p>If the argument is positive infinity, the result is 858 * {@code 0x7ff0000000000000L}. 859 * 860 * <p>If the argument is negative infinity, the result is 861 * {@code 0xfff0000000000000L}. 862 * 863 * <p>If the argument is NaN, the result is the {@code long} 864 * integer representing the actual NaN value. Unlike the 865 * {@code doubleToLongBits} method, 866 * {@code doubleToRawLongBits} does not collapse all the bit 867 * patterns encoding a NaN to a single "canonical" NaN 868 * value. 869 * 870 * <p>In all cases, the result is a {@code long} integer that, 871 * when given to the {@link #longBitsToDouble(long)} method, will 872 * produce a floating-point value the same as the argument to 873 * {@code doubleToRawLongBits}. 874 * 875 * @param value a {@code double} precision floating-point number. 876 * @return the bits that represent the floating-point number. 877 * @since 1.3 878 */ 879 public static native long doubleToRawLongBits(double value); 880 881 /** 882 * Returns the {@code double} value corresponding to a given 883 * bit representation. 884 * The argument is considered to be a representation of a 885 * floating-point value according to the IEEE 754 floating-point 886 * "double format" bit layout. 887 * 888 * <p>If the argument is {@code 0x7ff0000000000000L}, the result 889 * is positive infinity. 890 * 891 * <p>If the argument is {@code 0xfff0000000000000L}, the result 892 * is negative infinity. 893 * 894 * <p>If the argument is any value in the range 895 * {@code 0x7ff0000000000001L} through 896 * {@code 0x7fffffffffffffffL} or in the range 897 * {@code 0xfff0000000000001L} through 898 * {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE 899 * 754 floating-point operation provided by Java can distinguish 900 * between two NaN values of the same type with different bit 901 * patterns. Distinct values of NaN are only distinguishable by 902 * use of the {@code Double.doubleToRawLongBits} method. 903 * 904 * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three 905 * values that can be computed from the argument: 906 * 907 * <blockquote><pre> 908 * int s = ((bits >> 63) == 0) ? 1 : -1; 909 * int e = (int)((bits >> 52) & 0x7ffL); 910 * long m = (e == 0) ? 911 * (bits & 0xfffffffffffffL) << 1 : 912 * (bits & 0xfffffffffffffL) | 0x10000000000000L; 913 * </pre></blockquote> 914 * 915 * Then the floating-point result equals the value of the mathematical 916 * expression <i>s</i>·<i>m</i>·2<sup><i>e</i>-1075</sup>. 917 * 918 * <p>Note that this method may not be able to return a 919 * {@code double} NaN with exactly same bit pattern as the 920 * {@code long} argument. IEEE 754 distinguishes between two 921 * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The 922 * differences between the two kinds of NaN are generally not 923 * visible in Java. Arithmetic operations on signaling NaNs turn 924 * them into quiet NaNs with a different, but often similar, bit 925 * pattern. However, on some processors merely copying a 926 * signaling NaN also performs that conversion. In particular, 927 * copying a signaling NaN to return it to the calling method 928 * may perform this conversion. So {@code longBitsToDouble} 929 * may not be able to return a {@code double} with a 930 * signaling NaN bit pattern. Consequently, for some 931 * {@code long} values, 932 * {@code doubleToRawLongBits(longBitsToDouble(start))} may 933 * <i>not</i> equal {@code start}. Moreover, which 934 * particular bit patterns represent signaling NaNs is platform 935 * dependent; although all NaN bit patterns, quiet or signaling, 936 * must be in the NaN range identified above. 937 * 938 * @param bits any {@code long} integer. 939 * @return the {@code double} floating-point value with the same 940 * bit pattern. 941 */ 942 public static native double longBitsToDouble(long bits); 943 944 /** 945 * Compares two {@code Double} objects numerically. There 946 * are two ways in which comparisons performed by this method 947 * differ from those performed by the Java language numerical 948 * comparison operators ({@code <, <=, ==, >=, >}) 949 * when applied to primitive {@code double} values: 950 * <ul><li> 951 * {@code Double.NaN} is considered by this method 952 * to be equal to itself and greater than all other 953 * {@code double} values (including 954 * {@code Double.POSITIVE_INFINITY}). 955 * <li> 956 * {@code 0.0d} is considered by this method to be greater 957 * than {@code -0.0d}. 958 * </ul> 959 * This ensures that the <i>natural ordering</i> of 960 * {@code Double} objects imposed by this method is <i>consistent 961 * with equals</i>. 962 * 963 * @param anotherDouble the {@code Double} to be compared. 964 * @return the value {@code 0} if {@code anotherDouble} is 965 * numerically equal to this {@code Double}; a value 966 * less than {@code 0} if this {@code Double} 967 * is numerically less than {@code anotherDouble}; 968 * and a value greater than {@code 0} if this 969 * {@code Double} is numerically greater than 970 * {@code anotherDouble}. 971 * 972 * @since 1.2 973 */ 974 public int compareTo(Double anotherDouble) { 975 return Double.compare(value, anotherDouble.value); 976 } 977 978 /** 979 * Compares the two specified {@code double} values. The sign 980 * of the integer value returned is the same as that of the 981 * integer that would be returned by the call: 982 * <pre> 983 * new Double(d1).compareTo(new Double(d2)) 984 * </pre> 985 * 986 * @param d1 the first {@code double} to compare 987 * @param d2 the second {@code double} to compare 988 * @return the value {@code 0} if {@code d1} is 989 * numerically equal to {@code d2}; a value less than 990 * {@code 0} if {@code d1} is numerically less than 991 * {@code d2}; and a value greater than {@code 0} 992 * if {@code d1} is numerically greater than 993 * {@code d2}. 994 * @since 1.4 995 */ 996 public static int compare(double d1, double d2) { 997 if (d1 < d2) 998 return -1; // Neither val is NaN, thisVal is smaller 999 if (d1 > d2) 1000 return 1; // Neither val is NaN, thisVal is larger 1001 1002 // Cannot use doubleToRawLongBits because of possibility of NaNs. 1003 long thisBits = Double.doubleToLongBits(d1); 1004 long anotherBits = Double.doubleToLongBits(d2); 1005 1006 return (thisBits == anotherBits ? 0 : // Values are equal 1007 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1008 1)); // (0.0, -0.0) or (NaN, !NaN) 1009 } 1010 1011 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1012 private static final long serialVersionUID = -9172774392245257468L; 1013 }