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