001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.base.Preconditions.checkPositionIndexes; 021import static com.google.common.base.Strings.lenientFormat; 022import static java.lang.Double.NEGATIVE_INFINITY; 023import static java.lang.Double.POSITIVE_INFINITY; 024 025import com.google.common.annotations.Beta; 026import com.google.common.annotations.GwtCompatible; 027import com.google.common.annotations.GwtIncompatible; 028import com.google.common.base.Converter; 029import java.io.Serializable; 030import java.util.AbstractList; 031import java.util.Arrays; 032import java.util.Collection; 033import java.util.Collections; 034import java.util.Comparator; 035import java.util.List; 036import java.util.RandomAccess; 037import java.util.Spliterator; 038import java.util.Spliterators; 039import org.checkerframework.checker.nullness.qual.Nullable; 040 041/** 042 * Static utility methods pertaining to {@code double} primitives, that are not already found in 043 * either {@link Double} or {@link Arrays}. 044 * 045 * <p>See the Guava User Guide article on <a 046 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 047 * 048 * @author Kevin Bourrillion 049 * @since 1.0 050 */ 051@GwtCompatible(emulated = true) 052public final class Doubles extends DoublesMethodsForWeb { 053 private Doubles() {} 054 055 /** 056 * The number of bytes required to represent a primitive {@code double} value. 057 * 058 * <p><b>Java 8 users:</b> use {@link Double#BYTES} instead. 059 * 060 * @since 10.0 061 */ 062 public static final int BYTES = Double.SIZE / Byte.SIZE; 063 064 /** 065 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double) 066 * value).hashCode()}. 067 * 068 * <p><b>Java 8 users:</b> use {@link Double#hashCode(double)} instead. 069 * 070 * @param value a primitive {@code double} value 071 * @return a hash code for the value 072 */ 073 public static int hashCode(double value) { 074 return ((Double) value).hashCode(); 075 // TODO(kevinb): do it this way when we can (GWT problem): 076 // long bits = Double.doubleToLongBits(value); 077 // return (int) (bits ^ (bits >>> 32)); 078 } 079 080 /** 081 * Compares the two specified {@code double} values. The sign of the value returned is the same as 082 * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that 083 * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}. 084 * 085 * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is 086 * provided for consistency with the other primitive types, whose compare methods were not added 087 * to the JDK until JDK 7. 088 * 089 * @param a the first {@code double} to compare 090 * @param b the second {@code double} to compare 091 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 092 * greater than {@code b}; or zero if they are equal 093 */ 094 public static int compare(double a, double b) { 095 return Double.compare(a, b); 096 } 097 098 /** 099 * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not 100 * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}. 101 * 102 * <p><b>Java 8 users:</b> use {@link Double#isFinite(double)} instead. 103 * 104 * @since 10.0 105 */ 106 public static boolean isFinite(double value) { 107 return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; 108 } 109 110 /** 111 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note 112 * that this always returns {@code false} when {@code target} is {@code NaN}. 113 * 114 * @param array an array of {@code double} values, possibly empty 115 * @param target a primitive {@code double} value 116 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 117 */ 118 public static boolean contains(double[] array, double target) { 119 for (double value : array) { 120 if (value == target) { 121 return true; 122 } 123 } 124 return false; 125 } 126 127 /** 128 * Returns the index of the first appearance of the value {@code target} in {@code array}. Note 129 * that this always returns {@code -1} when {@code target} is {@code NaN}. 130 * 131 * @param array an array of {@code double} values, possibly empty 132 * @param target a primitive {@code double} value 133 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 134 * such index exists. 135 */ 136 public static int indexOf(double[] array, double target) { 137 return indexOf(array, target, 0, array.length); 138 } 139 140 // TODO(kevinb): consider making this public 141 private static int indexOf(double[] array, double target, int start, int end) { 142 for (int i = start; i < end; i++) { 143 if (array[i] == target) { 144 return i; 145 } 146 } 147 return -1; 148 } 149 150 /** 151 * Returns the start position of the first occurrence of the specified {@code target} within 152 * {@code array}, or {@code -1} if there is no such occurrence. 153 * 154 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 155 * i, i + target.length)} contains exactly the same elements as {@code target}. 156 * 157 * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. 158 * 159 * @param array the array to search for the sequence {@code target} 160 * @param target the array to search for as a sub-sequence of {@code array} 161 */ 162 public static int indexOf(double[] array, double[] target) { 163 checkNotNull(array, "array"); 164 checkNotNull(target, "target"); 165 if (target.length == 0) { 166 return 0; 167 } 168 169 outer: 170 for (int i = 0; i < array.length - target.length + 1; i++) { 171 for (int j = 0; j < target.length; j++) { 172 if (array[i + j] != target[j]) { 173 continue outer; 174 } 175 } 176 return i; 177 } 178 return -1; 179 } 180 181 /** 182 * Returns the index of the last appearance of the value {@code target} in {@code array}. Note 183 * that this always returns {@code -1} when {@code target} is {@code NaN}. 184 * 185 * @param array an array of {@code double} values, possibly empty 186 * @param target a primitive {@code double} value 187 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 188 * such index exists. 189 */ 190 public static int lastIndexOf(double[] array, double target) { 191 return lastIndexOf(array, target, 0, array.length); 192 } 193 194 // TODO(kevinb): consider making this public 195 private static int lastIndexOf(double[] array, double target, int start, int end) { 196 for (int i = end - 1; i >= start; i--) { 197 if (array[i] == target) { 198 return i; 199 } 200 } 201 return -1; 202 } 203 204 /** 205 * Returns the least value present in {@code array}, using the same rules of comparison as {@link 206 * Math#min(double, double)}. 207 * 208 * @param array a <i>nonempty</i> array of {@code double} values 209 * @return the value present in {@code array} that is less than or equal to every other value in 210 * the array 211 * @throws IllegalArgumentException if {@code array} is empty 212 */ 213 @GwtIncompatible( 214 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 215 public static double min(double... array) { 216 checkArgument(array.length > 0); 217 double min = array[0]; 218 for (int i = 1; i < array.length; i++) { 219 min = Math.min(min, array[i]); 220 } 221 return min; 222 } 223 224 /** 225 * Returns the greatest value present in {@code array}, using the same rules of comparison as 226 * {@link Math#max(double, double)}. 227 * 228 * @param array a <i>nonempty</i> array of {@code double} values 229 * @return the value present in {@code array} that is greater than or equal to every other value 230 * in the array 231 * @throws IllegalArgumentException if {@code array} is empty 232 */ 233 @GwtIncompatible( 234 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 235 public static double max(double... array) { 236 checkArgument(array.length > 0); 237 double max = array[0]; 238 for (int i = 1; i < array.length; i++) { 239 max = Math.max(max, array[i]); 240 } 241 return max; 242 } 243 244 /** 245 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 246 * 247 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 248 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 249 * value} is greater than {@code max}, {@code max} is returned. 250 * 251 * @param value the {@code double} value to constrain 252 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 253 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 254 * @throws IllegalArgumentException if {@code min > max} 255 * @since 21.0 256 */ 257 @Beta 258 public static double constrainToRange(double value, double min, double max) { 259 // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984 260 // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max). 261 if (min <= max) { 262 return Math.min(Math.max(value, min), max); 263 } 264 throw new IllegalArgumentException( 265 lenientFormat("min (%s) must be less than or equal to max (%s)", min, max)); 266 } 267 268 /** 269 * Returns the values from each provided array combined into a single array. For example, {@code 270 * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b, 271 * c}}. 272 * 273 * @param arrays zero or more {@code double} arrays 274 * @return a single array containing all the values from the source arrays, in order 275 */ 276 public static double[] concat(double[]... arrays) { 277 int length = 0; 278 for (double[] array : arrays) { 279 length += array.length; 280 } 281 double[] result = new double[length]; 282 int pos = 0; 283 for (double[] array : arrays) { 284 System.arraycopy(array, 0, result, pos, array.length); 285 pos += array.length; 286 } 287 return result; 288 } 289 290 private static final class DoubleConverter extends Converter<String, Double> 291 implements Serializable { 292 static final DoubleConverter INSTANCE = new DoubleConverter(); 293 294 @Override 295 protected Double doForward(String value) { 296 return Double.valueOf(value); 297 } 298 299 @Override 300 protected String doBackward(Double value) { 301 return value.toString(); 302 } 303 304 @Override 305 public String toString() { 306 return "Doubles.stringConverter()"; 307 } 308 309 private Object readResolve() { 310 return INSTANCE; 311 } 312 313 private static final long serialVersionUID = 1; 314 } 315 316 /** 317 * Returns a serializable converter object that converts between strings and doubles using {@link 318 * Double#valueOf} and {@link Double#toString()}. 319 * 320 * @since 16.0 321 */ 322 @Beta 323 public static Converter<String, Double> stringConverter() { 324 return DoubleConverter.INSTANCE; 325 } 326 327 /** 328 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 329 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 330 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 331 * returned, containing the values of {@code array}, and zeroes in the remaining places. 332 * 333 * @param array the source array 334 * @param minLength the minimum length the returned array must guarantee 335 * @param padding an extra amount to "grow" the array by if growth is necessary 336 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 337 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 338 * minLength} 339 */ 340 public static double[] ensureCapacity(double[] array, int minLength, int padding) { 341 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 342 checkArgument(padding >= 0, "Invalid padding: %s", padding); 343 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 344 } 345 346 /** 347 * Returns a string containing the supplied {@code double} values, converted to strings as 348 * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example, 349 * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}. 350 * 351 * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT 352 * sometimes. In the previous example, it returns the string {@code "1-2-3"}. 353 * 354 * @param separator the text that should appear between consecutive values in the resulting string 355 * (but not at the start or end) 356 * @param array an array of {@code double} values, possibly empty 357 */ 358 public static String join(String separator, double... array) { 359 checkNotNull(separator); 360 if (array.length == 0) { 361 return ""; 362 } 363 364 // For pre-sizing a builder, just get the right order of magnitude 365 StringBuilder builder = new StringBuilder(array.length * 12); 366 builder.append(array[0]); 367 for (int i = 1; i < array.length; i++) { 368 builder.append(separator).append(array[i]); 369 } 370 return builder.toString(); 371 } 372 373 /** 374 * Returns a comparator that compares two {@code double} arrays <a 375 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 376 * compares, using {@link #compare(double, double)}), the first pair of values that follow any 377 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 378 * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. 379 * 380 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 381 * support only identity equality), but it is consistent with {@link Arrays#equals(double[], 382 * double[])}. 383 * 384 * @since 2.0 385 */ 386 public static Comparator<double[]> lexicographicalComparator() { 387 return LexicographicalComparator.INSTANCE; 388 } 389 390 private enum LexicographicalComparator implements Comparator<double[]> { 391 INSTANCE; 392 393 @Override 394 public int compare(double[] left, double[] right) { 395 int minLength = Math.min(left.length, right.length); 396 for (int i = 0; i < minLength; i++) { 397 int result = Double.compare(left[i], right[i]); 398 if (result != 0) { 399 return result; 400 } 401 } 402 return left.length - right.length; 403 } 404 405 @Override 406 public String toString() { 407 return "Doubles.lexicographicalComparator()"; 408 } 409 } 410 411 /** 412 * Sorts the elements of {@code array} in descending order. 413 * 414 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 415 * all NaN values as equal and 0.0 as greater than -0.0. 416 * 417 * @since 23.1 418 */ 419 public static void sortDescending(double[] array) { 420 checkNotNull(array); 421 sortDescending(array, 0, array.length); 422 } 423 424 /** 425 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 426 * exclusive in descending order. 427 * 428 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 429 * all NaN values as equal and 0.0 as greater than -0.0. 430 * 431 * @since 23.1 432 */ 433 public static void sortDescending(double[] array, int fromIndex, int toIndex) { 434 checkNotNull(array); 435 checkPositionIndexes(fromIndex, toIndex, array.length); 436 Arrays.sort(array, fromIndex, toIndex); 437 reverse(array, fromIndex, toIndex); 438 } 439 440 /** 441 * Reverses the elements of {@code array}. This is equivalent to {@code 442 * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient. 443 * 444 * @since 23.1 445 */ 446 public static void reverse(double[] array) { 447 checkNotNull(array); 448 reverse(array, 0, array.length); 449 } 450 451 /** 452 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 453 * exclusive. This is equivalent to {@code 454 * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be 455 * more efficient. 456 * 457 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 458 * {@code toIndex > fromIndex} 459 * @since 23.1 460 */ 461 public static void reverse(double[] array, int fromIndex, int toIndex) { 462 checkNotNull(array); 463 checkPositionIndexes(fromIndex, toIndex, array.length); 464 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 465 double tmp = array[i]; 466 array[i] = array[j]; 467 array[j] = tmp; 468 } 469 } 470 471 /** 472 * Returns an array containing each value of {@code collection}, converted to a {@code double} 473 * value in the manner of {@link Number#doubleValue}. 474 * 475 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 476 * Calling this method is as thread-safe as calling that method. 477 * 478 * @param collection a collection of {@code Number} instances 479 * @return an array containing the same values as {@code collection}, in the same order, converted 480 * to primitives 481 * @throws NullPointerException if {@code collection} or any of its elements is null 482 * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) 483 */ 484 public static double[] toArray(Collection<? extends Number> collection) { 485 if (collection instanceof DoubleArrayAsList) { 486 return ((DoubleArrayAsList) collection).toDoubleArray(); 487 } 488 489 Object[] boxedArray = collection.toArray(); 490 int len = boxedArray.length; 491 double[] array = new double[len]; 492 for (int i = 0; i < len; i++) { 493 // checkNotNull for GWT (do not optimize) 494 array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); 495 } 496 return array; 497 } 498 499 /** 500 * Returns a fixed-size list backed by the specified array, similar to {@link 501 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 502 * set a value to {@code null} will result in a {@link NullPointerException}. 503 * 504 * <p>The returned list maintains the values, but not the identities, of {@code Double} objects 505 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 506 * the returned list is unspecified. 507 * 508 * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} 509 * is used as a parameter to any of its methods. 510 * 511 * <p><b>Note:</b> when possible, you should represent your data as an {@link 512 * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view. 513 * 514 * @param backingArray the array to back the list 515 * @return a list view of the array 516 */ 517 public static List<Double> asList(double... backingArray) { 518 if (backingArray.length == 0) { 519 return Collections.emptyList(); 520 } 521 return new DoubleArrayAsList(backingArray); 522 } 523 524 @GwtCompatible 525 private static class DoubleArrayAsList extends AbstractList<Double> 526 implements RandomAccess, Serializable { 527 final double[] array; 528 final int start; 529 final int end; 530 531 DoubleArrayAsList(double[] array) { 532 this(array, 0, array.length); 533 } 534 535 DoubleArrayAsList(double[] array, int start, int end) { 536 this.array = array; 537 this.start = start; 538 this.end = end; 539 } 540 541 @Override 542 public int size() { 543 return end - start; 544 } 545 546 @Override 547 public boolean isEmpty() { 548 return false; 549 } 550 551 @Override 552 public Double get(int index) { 553 checkElementIndex(index, size()); 554 return array[start + index]; 555 } 556 557 @Override 558 public Spliterator.OfDouble spliterator() { 559 return Spliterators.spliterator(array, start, end, 0); 560 } 561 562 @Override 563 public boolean contains(Object target) { 564 // Overridden to prevent a ton of boxing 565 return (target instanceof Double) 566 && Doubles.indexOf(array, (Double) target, start, end) != -1; 567 } 568 569 @Override 570 public int indexOf(Object target) { 571 // Overridden to prevent a ton of boxing 572 if (target instanceof Double) { 573 int i = Doubles.indexOf(array, (Double) target, start, end); 574 if (i >= 0) { 575 return i - start; 576 } 577 } 578 return -1; 579 } 580 581 @Override 582 public int lastIndexOf(Object target) { 583 // Overridden to prevent a ton of boxing 584 if (target instanceof Double) { 585 int i = Doubles.lastIndexOf(array, (Double) target, start, end); 586 if (i >= 0) { 587 return i - start; 588 } 589 } 590 return -1; 591 } 592 593 @Override 594 public Double set(int index, Double element) { 595 checkElementIndex(index, size()); 596 double oldValue = array[start + index]; 597 // checkNotNull for GWT (do not optimize) 598 array[start + index] = checkNotNull(element); 599 return oldValue; 600 } 601 602 @Override 603 public List<Double> subList(int fromIndex, int toIndex) { 604 int size = size(); 605 checkPositionIndexes(fromIndex, toIndex, size); 606 if (fromIndex == toIndex) { 607 return Collections.emptyList(); 608 } 609 return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); 610 } 611 612 @Override 613 public boolean equals(@Nullable Object object) { 614 if (object == this) { 615 return true; 616 } 617 if (object instanceof DoubleArrayAsList) { 618 DoubleArrayAsList that = (DoubleArrayAsList) object; 619 int size = size(); 620 if (that.size() != size) { 621 return false; 622 } 623 for (int i = 0; i < size; i++) { 624 if (array[start + i] != that.array[that.start + i]) { 625 return false; 626 } 627 } 628 return true; 629 } 630 return super.equals(object); 631 } 632 633 @Override 634 public int hashCode() { 635 int result = 1; 636 for (int i = start; i < end; i++) { 637 result = 31 * result + Doubles.hashCode(array[i]); 638 } 639 return result; 640 } 641 642 @Override 643 public String toString() { 644 StringBuilder builder = new StringBuilder(size() * 12); 645 builder.append('[').append(array[start]); 646 for (int i = start + 1; i < end; i++) { 647 builder.append(", ").append(array[i]); 648 } 649 return builder.append(']').toString(); 650 } 651 652 double[] toDoubleArray() { 653 return Arrays.copyOfRange(array, start, end); 654 } 655 656 private static final long serialVersionUID = 0; 657 } 658 659 /** 660 * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating 661 * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs 662 * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug. 663 */ 664 @GwtIncompatible // regular expressions 665 static final 666 java.util.regex.Pattern 667 FLOATING_POINT_PATTERN = fpPattern(); 668 669 @GwtIncompatible // regular expressions 670 private static 671 java.util.regex.Pattern 672 fpPattern() { 673 /* 674 * We use # instead of * for possessive quantifiers. This lets us strip them out when building 675 * the regex for RE2 (which doesn't support them) but leave them in when building it for 676 * java.util.regex (where we want them in order to avoid catastrophic backtracking). 677 */ 678 String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)"; 679 String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?"; 680 String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)"; 681 String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?"; 682 String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; 683 fpPattern = 684 fpPattern.replace( 685 "#", 686 "+" 687 ); 688 return 689 java.util.regex.Pattern 690 .compile(fpPattern); 691 } 692 693 /** 694 * Parses the specified string as a double-precision floating point value. The ASCII character 695 * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 696 * 697 * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of 698 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link 699 * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. 700 * 701 * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures 702 * are expected. 703 * 704 * @param string the string representation of a {@code double} value 705 * @return the floating point value represented by {@code string}, or {@code null} if {@code 706 * string} has a length of zero or cannot be parsed as a {@code double} value 707 * @throws NullPointerException if {@code string} is {@code null} 708 * @since 14.0 709 */ 710 @Beta 711 @GwtIncompatible // regular expressions 712 public static @Nullable Double tryParse(String string) { 713 if (FLOATING_POINT_PATTERN.matcher(string).matches()) { 714 // TODO(lowasser): could be potentially optimized, but only with 715 // extensive testing 716 try { 717 return Double.parseDouble(string); 718 } catch (NumberFormatException e) { 719 // Double.parseDouble has changed specs several times, so fall through 720 // gracefully 721 } 722 } 723 return null; 724 } 725}