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