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