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.NEGATIVE_INFINITY; 023import static java.lang.Float.POSITIVE_INFINITY; 024 025import com.google.common.annotations.GwtCompatible; 026import com.google.common.annotations.GwtIncompatible; 027import com.google.common.base.Converter; 028import com.google.errorprone.annotations.InlineMe; 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 org.jspecify.annotations.Nullable; 038 039/** 040 * Static utility methods pertaining to {@code float} primitives, that are not already found in 041 * either {@link Float} or {@link Arrays}. 042 * 043 * <p>See the Guava User Guide article on <a 044 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 045 * 046 * @author Kevin Bourrillion 047 * @since 1.0 048 */ 049@GwtCompatible(emulated = true) 050public final class Floats extends FloatsMethodsForWeb { 051 private Floats() {} 052 053 /** 054 * The number of bytes required to represent a primitive {@code float} value. 055 * 056 * <p><b>Java 8+ users:</b> use {@link Float#BYTES} instead. 057 * 058 * @since 10.0 059 */ 060 public static final int BYTES = Float.SIZE / Byte.SIZE; 061 062 /** 063 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Float) 064 * value).hashCode()}. 065 * 066 * <p><b>Java 8+ users:</b> use {@link Float#hashCode(float)} instead. 067 * 068 * @param value a primitive {@code float} value 069 * @return a hash code for the value 070 */ 071 public static int hashCode(float value) { 072 // TODO(kevinb): is there a better way, that's still gwt-safe? 073 return ((Float) value).hashCode(); 074 } 075 076 /** 077 * Compares the two specified {@code float} values using {@link Float#compare(float, float)}. You 078 * may prefer to invoke that method directly; this method exists only for consistency with the 079 * other utilities in this package. 080 * 081 * <p><b>Note:</b> this method simply delegates to the JDK method {@link Float#compare}. It is 082 * provided for consistency with the other primitive types, whose compare methods were not added 083 * to the JDK until JDK 7. 084 * 085 * @param a the first {@code float} to compare 086 * @param b the second {@code float} to compare 087 * @return the result of invoking {@link Float#compare(float, float)} 088 */ 089 @InlineMe(replacement = "Float.compare(a, b)") 090 public static int compare(float a, float b) { 091 return Float.compare(a, b); 092 } 093 094 /** 095 * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not 096 * necessarily implemented as, {@code !(Float.isInfinite(value) || Float.isNaN(value))}. 097 * 098 * <p><b>Java 8+ users:</b> use {@link Float#isFinite(float)} instead. 099 * 100 * @since 10.0 101 */ 102 public static boolean isFinite(float value) { 103 return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; 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 {@code Math.clamp} 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 System.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 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 Arrays.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 Collections.emptyList(); 575 } 576 return new FloatArrayAsList(backingArray); 577 } 578 579 @GwtCompatible 580 private static class FloatArrayAsList extends AbstractList<Float> 581 implements RandomAccess, Serializable { 582 final float[] array; 583 final int start; 584 final int end; 585 586 FloatArrayAsList(float[] array) { 587 this(array, 0, array.length); 588 } 589 590 FloatArrayAsList(float[] array, int start, int end) { 591 this.array = array; 592 this.start = start; 593 this.end = end; 594 } 595 596 @Override 597 public int size() { 598 return end - start; 599 } 600 601 @Override 602 public boolean isEmpty() { 603 return false; 604 } 605 606 @Override 607 public Float get(int index) { 608 checkElementIndex(index, size()); 609 return array[start + index]; 610 } 611 612 @Override 613 public boolean contains(@Nullable Object target) { 614 // Overridden to prevent a ton of boxing 615 return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; 616 } 617 618 @Override 619 public int indexOf(@Nullable Object target) { 620 // Overridden to prevent a ton of boxing 621 if (target instanceof Float) { 622 int i = Floats.indexOf(array, (Float) target, start, end); 623 if (i >= 0) { 624 return i - start; 625 } 626 } 627 return -1; 628 } 629 630 @Override 631 public int lastIndexOf(@Nullable Object target) { 632 // Overridden to prevent a ton of boxing 633 if (target instanceof Float) { 634 int i = Floats.lastIndexOf(array, (Float) target, start, end); 635 if (i >= 0) { 636 return i - start; 637 } 638 } 639 return -1; 640 } 641 642 @Override 643 public Float set(int index, Float element) { 644 checkElementIndex(index, size()); 645 float oldValue = array[start + index]; 646 // checkNotNull for GWT (do not optimize) 647 array[start + index] = checkNotNull(element); 648 return oldValue; 649 } 650 651 @Override 652 public List<Float> subList(int fromIndex, int toIndex) { 653 int size = size(); 654 checkPositionIndexes(fromIndex, toIndex, size); 655 if (fromIndex == toIndex) { 656 return Collections.emptyList(); 657 } 658 return new FloatArrayAsList(array, start + fromIndex, start + toIndex); 659 } 660 661 @Override 662 public boolean equals(@Nullable Object object) { 663 if (object == this) { 664 return true; 665 } 666 if (object instanceof FloatArrayAsList) { 667 FloatArrayAsList that = (FloatArrayAsList) object; 668 int size = size(); 669 if (that.size() != size) { 670 return false; 671 } 672 for (int i = 0; i < size; i++) { 673 if (array[start + i] != that.array[that.start + i]) { 674 return false; 675 } 676 } 677 return true; 678 } 679 return super.equals(object); 680 } 681 682 @Override 683 public int hashCode() { 684 int result = 1; 685 for (int i = start; i < end; i++) { 686 result = 31 * result + Floats.hashCode(array[i]); 687 } 688 return result; 689 } 690 691 @Override 692 public String toString() { 693 StringBuilder builder = new StringBuilder(size() * 12); 694 builder.append('[').append(array[start]); 695 for (int i = start + 1; i < end; i++) { 696 builder.append(", ").append(array[i]); 697 } 698 return builder.append(']').toString(); 699 } 700 701 float[] toFloatArray() { 702 return Arrays.copyOfRange(array, start, end); 703 } 704 705 private static final long serialVersionUID = 0; 706 } 707 708 /** 709 * Parses the specified string as a single-precision floating point value. The ASCII character 710 * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 711 * 712 * <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of 713 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link 714 * Float#valueOf(String)}, except that leading and trailing whitespace is not permitted. 715 * 716 * <p>This implementation is likely to be faster than {@code Float.parseFloat} if many failures 717 * are expected. 718 * 719 * @param string the string representation of a {@code float} value 720 * @return the floating point value represented by {@code string}, or {@code null} if {@code 721 * string} has a length of zero or cannot be parsed as a {@code float} value 722 * @throws NullPointerException if {@code string} is {@code null} 723 * @since 14.0 724 */ 725 @GwtIncompatible // regular expressions 726 public static @Nullable Float tryParse(String string) { 727 if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { 728 // TODO(lowasser): could be potentially optimized, but only with 729 // extensive testing 730 try { 731 return Float.parseFloat(string); 732 } catch (NumberFormatException e) { 733 // Float.parseFloat has changed specs several times, so fall through 734 // gracefully 735 } 736 } 737 return null; 738 } 739}