Class Float

java.lang.Object
java.lang.Number
java.lang.Float
All Implemented Interfaces:
Serializable,Comparable<Float>,Constable,ConstantDesc

public final classFloatextendsNumberimplementsComparable<Float>,Constable,ConstantDesc
TheFloat class is thewrapper class for values of the primitivetypefloat. An object of typeFloat contains asingle field whose type isfloat.

In addition, this class provides several methods for converting afloat to aString and aString to afloat, as well as otherconstants and methods useful when dealing with afloat.

This is avalue-basedclass; programmers should treat instances that areequal as interchangeable and should notuse instances for synchronization, or unpredictable behavior mayoccur. For example, in a future release, synchronization may fail.

Floating-point Equality, Equivalence,and Comparison

The classjava.lang.Double has adiscussion of equality,equivalence, and comparison of floating-point values that isequally applicable tofloat values.

Decimal ↔ Binary Conversion Issues

Thediscussion of binary todecimal conversion issues injava.lang.Double is alsoapplicable tofloat values.
Since:
1.0
External Specifications
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final int
    The number of bytes used to represent afloat value,4.
    static final int
    Maximum exponent a finitefloat variable may have,127.
    static final float
    A constant holding the largest positive finite value of typefloat, (2-2-23)·2127.
    static final int
    Minimum exponent a normalizedfloat variable may have,-126.
    static final float
    A constant holding the smallest positive normal value of typefloat, 2-126.
    static final float
    A constant holding the smallest positive nonzero value of typefloat, 2-149.
    static final float
    A constant holding a Not-a-Number (NaN) value of typefloat.
    static final float
    A constant holding the negative infinity of typefloat.
    static final float
    A constant holding the positive infinity of typefloat.
    static final int
    The number of bits in the significand of afloat value,24.
    static final int
    The number of bits used to represent afloat value,32.
    static finalClass<Float>
    TheClass instance representing the primitive typefloat.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Float(double value)
    Deprecated.
    It is rarely appropriate to use this constructor.
    Float(float value)
    Deprecated.
    It is rarely appropriate to use this constructor.
    Deprecated.
    It is rarely appropriate to use this constructor.
  • Method Summary

    Modifier and Type
    Method
    Description
    byte
    Returns the value of thisFloat as abyte aftera narrowing primitive conversion.
    static int
    compare(float f1, float f2)
    Compares the two specifiedfloat values.
    int
    compareTo(Float anotherFloat)
    Compares twoFloat objects numerically.
    Returns anOptional containing the nominal descriptor for thisinstance, which is the instance itself.
    double
    Returns the value of thisFloat as adoubleafter a widening primitive conversion.
    boolean
    Compares this object against the specified object.
    static float
    float16ToFloat(short floatBinary16)
    Returns thefloat value closest to the numerical valueof the argument, a floating-point binary16 value encoded in ashort.
    static short
    floatToFloat16(float f)
    Returns the floating-point binary16 value, encoded in ashort, closest in value to the argument.
    static int
    floatToIntBits(float value)
    Returns a representation of the specified floating-point valueaccording to the IEEE 754 floating-point "single format" bitlayout.
    static int
    floatToRawIntBits(float value)
    Returns a representation of the specified floating-point valueaccording to the IEEE 754 floating-point "single format" bitlayout, preserving Not-a-Number (NaN) values.
    float
    Returns thefloat value of thisFloat object.
    int
    Returns a hash code for thisFloat object.
    static int
    hashCode(float value)
    Returns a hash code for afloat value; compatible withFloat.hashCode().
    static float
    intBitsToFloat(int bits)
    Returns thefloat value corresponding to a givenbit representation.
    int
    Returns the value of thisFloat as anint aftera narrowing primitive conversion.
    static boolean
    isFinite(float f)
    Returnstrue if the argument is a finite floating-pointvalue; returnsfalse otherwise (for NaN and infinityarguments).
    boolean
    Returnstrue if thisFloat value isinfinitely large in magnitude,false otherwise.
    static boolean
    isInfinite(float v)
    Returnstrue if the specified number is infinitelylarge in magnitude,false otherwise.
    boolean
    Returnstrue if thisFloat value is aNot-a-Number (NaN),false otherwise.
    static boolean
    isNaN(float v)
    Returnstrue if the specified number is aNot-a-Number (NaN) value,false otherwise.
    long
    Returns value of thisFloat as along after anarrowing primitive conversion.
    static float
    max(float a, float b)
    Returns the greater of twofloat valuesas if by callingMath.max.
    static float
    min(float a, float b)
    Returns the smaller of twofloat valuesas if by callingMath.min.
    static float
    Returns a newfloat initialized to the valuerepresented by the specifiedString, as performedby thevalueOf method of classFloat.
    Resolves this instance as aConstantDesc, the result of which isthe instance itself.
    short
    Returns the value of thisFloat as ashortafter a narrowing primitive conversion.
    static float
    sum(float a, float b)
    Adds twofloat values together as per the + operator.
    staticString
    toHexString(float f)
    Returns a hexadecimal string representation of thefloat argument.
    Returns a string representation of thisFloat object.
    staticString
    toString(float f)
    Returns a string representation of thefloatargument.
    staticFloat
    valueOf(float f)
    Returns aFloat instance representing the specifiedfloat value.
    staticFloat
    Returns aFloat object holding thefloat value represented by the argument strings.
  • Field Details

    • POSITIVE_INFINITY

      public static final float POSITIVE_INFINITY
      A constant holding the positive infinity of typefloat. It is equal to the value returned byFloat.intBitsToFloat(0x7f800000).
      See Also:
    • NEGATIVE_INFINITY

      public static final float NEGATIVE_INFINITY
      A constant holding the negative infinity of typefloat. It is equal to the value returned byFloat.intBitsToFloat(0xff800000).
      See Also:
    • NaN

      public static final float NaN
      A constant holding a Not-a-Number (NaN) value of typefloat.It isequivalentto the value returned byFloat.intBitsToFloat(0x7fc00000).
      See Also:
    • MAX_VALUE

      public static final float MAX_VALUE
      A constant holding the largest positive finite value of typefloat, (2-2-23)·2127.It is equal to the hexadecimal floating-point literal0x1.fffffeP+127f and also equal toFloat.intBitsToFloat(0x7f7fffff).
      See Also:
    • MIN_NORMAL

      public static final float MIN_NORMAL
      A constant holding the smallest positive normal value of typefloat, 2-126. It is equal to thehexadecimal floating-point literal0x1.0p-126f and alsoequal toFloat.intBitsToFloat(0x00800000).
      Since:
      1.6
      See Also:
    • MIN_VALUE

      public static final float MIN_VALUE
      A constant holding the smallest positive nonzero value of typefloat, 2-149. It is equal to thehexadecimal floating-point literal0x0.000002P-126fand also equal toFloat.intBitsToFloat(0x1).
      See Also:
    • SIZE

      public static final int SIZE
      The number of bits used to represent afloat value,32.
      Since:
      1.5
      See Also:
    • PRECISION

      public static final int PRECISION
      The number of bits in the significand of afloat value,24. This is the parameter N in section4.2.3 ofThe Java Language Specification.
      Since:
      19
      See Also:
    • MAX_EXPONENT

      public static final int MAX_EXPONENT
      Maximum exponent a finitefloat variable may have,127. It is equal to the value returned byMath.getExponent(Float.MAX_VALUE).
      Since:
      1.6
      See Also:
    • MIN_EXPONENT

      public static final int MIN_EXPONENT
      Minimum exponent a normalizedfloat variable may have,-126. It is equal to the value returned byMath.getExponent(Float.MIN_NORMAL).
      Since:
      1.6
      See Also:
    • BYTES

      public static final int BYTES
      The number of bytes used to represent afloat value,4.
      Since:
      1.8
      See Also:
    • TYPE

      public static final Class<Float> TYPE
      TheClass instance representing the primitive typefloat.
      Since:
      1.1
  • Constructor Details

    • Float

      @Deprecated(since="9")public Float(float value)
      Deprecated.
      It is rarely appropriate to use this constructor. The static factoryvalueOf(float) is generally a better choice, as it islikely to yield significantly better space and time performance.
      Constructs a newly allocatedFloat object thatrepresents the primitivefloat argument.
      Parameters:
      value - the value to be represented by theFloat.
    • Float

      @Deprecated(since="9")public Float(double value)
      Deprecated.
      It is rarely appropriate to use this constructor. Instead, use thestatic factory methodvalueOf(float) method as follows:Float.valueOf((float)value).
      Constructs a newly allocatedFloat object thatrepresents the argument converted to typefloat.
      Parameters:
      value - the value to be represented by theFloat.
    • Float

      @Deprecated(since="9")public Float(String s) throwsNumberFormatException
      Deprecated.
      It is rarely appropriate to use this constructor.UseparseFloat(String) to convert a string to afloat primitive, or usevalueOf(String)to convert a string to aFloat object.
      Constructs a newly allocatedFloat object thatrepresents the floating-point value of typefloatrepresented by the string. The string is converted to afloat value as if by thevalueOf method.
      Parameters:
      s - a string to be converted to aFloat.
      Throws:
      NumberFormatException - if the string does not contain a parsable number.
  • Method Details

    • toString

      public static String toString(float f)
      Returns a string representation of thefloatargument. All characters mentioned below are ASCII characters.
      • If the argument is NaN, the result is the string"NaN".
      • Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('\u002D'); if the sign is positive, no sign character appears in the result. As for the magnitudem:
        • Ifm is infinity, it is represented by the characters"Infinity"; thus, positive infinity produces the result"Infinity" and negative infinity produces the result"-Infinity".
        • Ifm is zero, it is represented by the characters"0.0"; thus, negative zero produces the result"-0.0" and positive zero produces the result"0.0".
        • Otherwisem is positive and finite.It is converted to a string in two stages:
          • Selection of a decimal:A well-defined decimaldmis selected to representm.This decimal is (almost always) theshortest one thatrounds tom according to the round to nearestrounding policy of IEEE 754 floating-point arithmetic.
          • Formatting as a string:The decimaldm is formatted as a string,either in plain or in computerized scientific notation,depending on its value.

      Adecimal is a number of the forms×10ifor some (unique) integerss > 0 andi such thats is not a multiple of 10.These integers are thesignificand andtheexponent, respectively, of the decimal.Thelength of the decimal is the (unique)positive integern meeting10n-1s < 10n.

      The decimaldm for a finite positivemis defined as follows:

      • LetR be the set of all decimals that round tomaccording to the usualround to nearest rounding policy ofIEEE 754 floating-point arithmetic.
      • Letp be the minimal length over all decimals inR.
      • Whenp ≥ 2, letT be the set of all decimalsinR with lengthp.Otherwise, letT be the set of all decimalsinR with length 1 or 2.
      • Definedm as the decimal inTthat is closest tom.Or if there are two such decimals inT,select the one with the even significand.

      The (uniquely) selected decimaldmis then formatted.Lets,i andn be the significand, exponent andlength ofdm, respectively.Further, lete =n +i - 1 and lets1snbe the usual decimal expansion ofs.Note thats1 ≠ 0andsn ≠ 0.Below, the decimal point'.' is'\u002E'and the exponent indicator'E' is'\u0045'.

      • Case -3 ≤e < 0:dm is formatted as0.00s1sn,where there are exactly -(n +i) zeroes betweenthe decimal point ands1.For example, 123 × 10-4 is formatted as0.0123.
      • Case 0 ≤e < 7:
        • Subcasei ≥ 0:dm is formatted ass1sn00.0,where there are exactlyi zeroesbetweensn and the decimal point.For example, 123 × 102 is formatted as12300.0.
        • Subcasei < 0:dm is formatted ass1sn+i.sn+i+1sn,where there are exactly -i digits to the right ofthe decimal point.For example, 123 × 10-1 is formatted as12.3.
      • Casee < -3 ore ≥ 7:computerized scientific notation is used to formatdm.Heree is formatted as byInteger.toString(int).
        • Subcasen = 1:dm is formatted ass1.0Ee.For example, 1 × 1023 is formatted as1.0E23.
        • Subcasen > 1:dm is formatted ass1.s2snEe.For example, 123 × 10-21 is formatted as1.23E-19.

      To create localized string representations of a floating-pointvalue, use subclasses ofNumberFormat.

      API Note:
      This method corresponds to the general functionality of theconvertToDecimalCharacter operation defined in IEEE 754;however, that operation is defined in terms of specifying thenumber of significand digits used in the conversion.Code to do such a conversion in the Java platform includesconverting thefloat to aBigDecimal exactly and then rounding theBigDecimal tothe desired number of digits; sample code:
      floatf = 0.1f;int digits = 15;BigDecimal bd = new BigDecimal(f);String result = bd.round(new MathContext(digits,  RoundingMode.HALF_UP));// 0.100000001490116
      Parameters:
      f - thefloat to be converted.
      Returns:
      a string representation of the argument.
    • toHexString

      public static String toHexString(float f)
      Returns a hexadecimal string representation of thefloat argument. All characters mentioned below areASCII characters.
      • If the argument is NaN, the result is the string "NaN".
      • Otherwise, the result is a string that represents the sign andmagnitude (absolute value) of the argument. If the sign is negative,the first character of the result is '-'('\u002D'); if the sign is positive, no sign characterappears in the result. As for the magnitudem:
        • Ifm is infinity, it is represented by the string"Infinity"; thus, positive infinity produces theresult"Infinity" and negative infinity producesthe result"-Infinity".
        • Ifm is zero, it is represented by the string"0x0.0p0"; thus, negative zero produces the result"-0x0.0p0" and positive zero produces the result"0x0.0p0".
        • Ifm is afloat value with anormalized representation, substrings are used to represent thesignificand and exponent fields. The significand isrepresented by the characters"0x1."followed by a lowercase hexadecimal representation of the restof the significand as a fraction. Trailing zeros in thehexadecimal representation are removed unless all the digitsare zero, in which case a single zero is used. Next, theexponent is represented by"p" followedby a decimal string of the unbiased exponent as if produced bya call toInteger.toString on theexponent value.
        • Ifm is afloat value with a subnormalrepresentation, the significand is represented by thecharacters"0x0." followed by ahexadecimal representation of the rest of the significand as afraction. Trailing zeros in the hexadecimal representation areremoved. Next, the exponent is represented by"p-126". Note that there must be atleast one nonzero digit in a subnormal significand.
      Examples
      Floating-point ValueHexadecimal String
      1.00x1.0p0
      -1.0-0x1.0p0
      2.00x1.0p1
      3.00x1.8p1
      0.50x1.0p-1
      0.250x1.0p-2
      Float.MAX_VALUE0x1.fffffep127
      Minimum Normal Value0x1.0p-126
      Maximum Subnormal Value0x0.fffffep-126
      Float.MIN_VALUE0x0.000002p-126
      API Note:
      This method corresponds to the convertToHexCharacter operationdefined in IEEE 754.
      Parameters:
      f - thefloat to be converted.
      Returns:
      a hex string representation of the argument.
      Since:
      1.5
    • valueOf

      public static Float valueOf(String s) throwsNumberFormatException
      Returns aFloat object holding thefloat value represented by the argument strings.

      Ifs isnull, then aNullPointerException is thrown.

      Leading and trailing whitespace characters insare ignored. Whitespace is removed as if by theString.trim() method; that is, both ASCII space and controlcharacters are removed. The rest ofs shouldconstitute aFloatValue as described by the lexicalsyntax rules:

      FloatValue:
      SignoptNaN
      SignoptInfinity
      Signopt FloatingPointLiteral
      Signopt HexFloatingPointLiteral
      SignedInteger
      HexFloatingPointLiteral:
      HexSignificand BinaryExponent FloatTypeSuffixopt
      HexSignificand:
      HexNumeral
      HexNumeral.
      0xHexDigitsopt. HexDigits
      0X HexDigitsopt.HexDigits
      BinaryExponent:
      BinaryExponentIndicator SignedInteger
      BinaryExponentIndicator:
      p
      P
      whereSign,FloatingPointLiteral,HexNumeral,HexDigits,SignedInteger andFloatTypeSuffix are as defined in the lexical structuresections ofThe Java Language Specification,except that underscores are not accepted between digits.Ifs does not have the form ofaFloatValue, then aNumberFormatExceptionis thrown. Otherwise,s is regarded asrepresenting an exact decimal value in the usual"computerized scientific notation" or as an exacthexadecimal value; this exact numerical value is thenconceptually converted to an "infinitely precise"binary value that is then rounded to typefloatby the usual round-to-nearest rule of IEEE 754 floating-pointarithmetic, which includes preserving the sign of a zerovalue.Note that the round-to-nearest rule also implies overflow andunderflow behaviour; if the exact value ofs is largeenough in magnitude (greater than or equal to (MAX_VALUE +ulp(MAX_VALUE)/2),rounding tofloat will result in an infinity and if theexact value ofs is small enough in magnitude (lessthan or equal toMIN_VALUE/2), rounding to float willresult in a zero.Finally, after rounding aFloat object representingthisfloat value is returned.

      Note that trailing format specifiers, specifiers thatdetermine the type of a floating-point literal(1.0f is afloat value;1.0d is adouble value), donot influence the results of this method. In otherwords, the numerical value of the input string is converteddirectly to the target floating-point type. In general, thetwo-step sequence of conversions, string todoublefollowed bydouble tofloat, isnot equivalent to converting a string directly tofloat. For example, if first converted to anintermediatedouble and then tofloat, the string
      "1.00000017881393421514957253748434595763683319091796875001d"
      results in thefloat value1.0000002f; if the string is converted directly tofloat,1.0000001f results.

      To avoid calling this method on an invalid string and havingaNumberFormatException be thrown, the documentationforDouble.valueOf lists a regularexpression which can be used to screen the input.

      API Note:
      To interpret localized string representations of afloating-point value, or string representations that havenon-ASCII digits, useNumberFormat. Forexample,
          NumberFormat.getInstance(l).parse(s).floatValue();
      wherel is the desired locale, orLocale.ROOT if locale insensitive., This method corresponds to the convertFromDecimalCharacter andconvertFromHexCharacter operations defined in IEEE 754.
      Parameters:
      s - the string to be parsed.
      Returns:
      aFloat object holding the value represented by theString argument.
      Throws:
      NumberFormatException - if the string does not contain a parsable number.
      See Also:
    • valueOf

      public static Float valueOf(float f)
      Returns aFloat instance representing the specifiedfloat value.If a newFloat instance is not required, this methodshould generally be used in preference to the constructorFloat(float), as this method is likely to yieldsignificantly better space and time performance by cachingfrequently requested values.
      Parameters:
      f - a float value.
      Returns:
      aFloat instance representingf.
      Since:
      1.5
    • parseFloat

      public static float parseFloat(String s) throwsNumberFormatException
      Returns a newfloat initialized to the valuerepresented by the specifiedString, as performedby thevalueOf method of classFloat.
      Parameters:
      s - the string to be parsed.
      Returns:
      thefloat value represented by the string argument.
      Throws:
      NullPointerException - if the string is null
      NumberFormatException - if the string does not contain a parsablefloat.
      Since:
      1.2
      See Also:
    • isNaN

      public static boolean isNaN(float v)
      Returnstrue if the specified number is aNot-a-Number (NaN) value,false otherwise.
      API Note:
      This method corresponds to the isNaN operation defined in IEEE754.
      Parameters:
      v - the value to be tested.
      Returns:
      true if the argument is NaN;false otherwise.
    • isInfinite

      public static boolean isInfinite(float v)
      Returnstrue if the specified number is infinitelylarge in magnitude,false otherwise.
      API Note:
      This method corresponds to the isInfinite operation defined inIEEE 754.
      Parameters:
      v - the value to be tested.
      Returns:
      true if the argument is positive infinity or negative infinity;false otherwise.
    • isFinite

      public static boolean isFinite(float f)
      Returnstrue if the argument is a finite floating-pointvalue; returnsfalse otherwise (for NaN and infinityarguments).
      API Note:
      This method corresponds to the isFinite operation defined inIEEE 754.
      Parameters:
      f - thefloat value to be tested
      Returns:
      true if the argument is a finitefloating-point value,false otherwise.
      Since:
      1.8
    • isNaN

      public boolean isNaN()
      Returnstrue if thisFloat value is aNot-a-Number (NaN),false otherwise.
      Returns:
      true if the value represented by this object is NaN;false otherwise.
    • isInfinite

      public boolean isInfinite()
      Returnstrue if thisFloat value isinfinitely large in magnitude,false otherwise.
      Returns:
      true if the value represented by this object is positive infinity or negative infinity;false otherwise.
    • toString

      public String toString()
      Returns a string representation of thisFloat object.The primitivefloat value represented by this objectis converted to aString exactly as if by the methodtoString of one argument.
      Overrides:
      toString in class Object
      Returns:
      aString representation of this object.
      See Also:
    • byteValue

      public byte byteValue()
      Returns the value of thisFloat as abyte aftera narrowing primitive conversion.
      Overrides:
      byteValue in class Number
      Returns:
      thefloat value represented by this object converted to typebyte
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • shortValue

      public short shortValue()
      Returns the value of thisFloat as ashortafter a narrowing primitive conversion.
      Overrides:
      shortValue in class Number
      Returns:
      thefloat value represented by this object converted to typeshort
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
      Since:
      1.1
    • intValue

      public int intValue()
      Returns the value of thisFloat as anint aftera narrowing primitive conversion.
      Specified by:
      intValue in class Number
      API Note:
      This method corresponds to the convertToIntegerTowardZerooperation defined in IEEE 754.
      Returns:
      thefloat value represented by this object converted to typeint
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • longValue

      public long longValue()
      Returns value of thisFloat as along after anarrowing primitive conversion.
      Specified by:
      longValue in class Number
      API Note:
      This method corresponds to the convertToIntegerTowardZerooperation defined in IEEE 754.
      Returns:
      thefloat value represented by this object converted to typelong
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • floatValue

      public float floatValue()
      Returns thefloat value of thisFloat object.
      Specified by:
      floatValue in class Number
      Returns:
      thefloat value represented by this object
    • doubleValue

      public double doubleValue()
      Returns the value of thisFloat as adoubleafter a widening primitive conversion.
      Specified by:
      doubleValue in class Number
      API Note:
      This method corresponds to the convertFormat operation definedin IEEE 754.
      Returns:
      thefloat value represented by this object converted to typedouble
      SeeJava Language Specification:
      5.1.2 Widening Primitive Conversion
    • hashCode

      public int hashCode()
      Returns a hash code for thisFloat object. Theresult is the integer bit representation, exactly as producedby the methodfloatToIntBits(float), of the primitivefloat value represented by thisFloatobject.
      Overrides:
      hashCode in class Object
      Returns:
      a hash code value for this object.
      See Also:
    • hashCode

      public static int hashCode(float value)
      Returns a hash code for afloat value; compatible withFloat.hashCode().
      Parameters:
      value - the value to hash
      Returns:
      a hash code value for afloat value.
      Since:
      1.8
    • equals

      public boolean equals(Object obj)
      Compares this object against the specified object. The resultistrue if and only if the argument is notnull and is aFloat object thatrepresents afloat with the same value as thefloat represented by this object. For thispurpose, twofloat values are considered to be thesame if and only if the methodfloatToIntBits(float)returns the identicalint value when applied toeach.
      Overrides:
      equals in class Object
      API Note:
      This method is defined in terms offloatToIntBits(float) rather than the== operator onfloat values since the== operator doesnot define an equivalence relation and to satisfy theequals contract an equivalencerelation must be implemented; seethis discussion for details of floating-point equality and equivalence.
      Parameters:
      obj - the object to be compared
      Returns:
      true if the objects are the same;false otherwise.
      SeeJava Language Specification:
      15.21.1 Numerical Equality Operators == and !=
      See Also:
    • floatToIntBits

      public static int floatToIntBits(float value)
      Returns a representation of the specified floating-point valueaccording to the IEEE 754 floating-point "single format" bitlayout.

      Bit 31 (the bit that is selected by the mask0x80000000) represents the sign of the floating-pointnumber.Bits 30-23 (the bits that are selected by the mask0x7f800000) represent the exponent.Bits 22-0 (the bits that are selected by the mask0x007fffff) represent the significand (sometimes calledthe mantissa) of the floating-point number.

      If the argument is positive infinity, the result is0x7f800000.

      If the argument is negative infinity, the result is0xff800000.

      If the argument is NaN, the result is0x7fc00000.

      In all cases, the result is an integer that, when given to theintBitsToFloat(int) method, will produce a floating-pointvalue the same as the argument tofloatToIntBits(except all NaN values are collapsed to a single"canonical" NaN value).

      Parameters:
      value - a floating-point number.
      Returns:
      the bits that represent the floating-point number.
    • floatToRawIntBits

      public static int floatToRawIntBits(float value)
      Returns a representation of the specified floating-point valueaccording to the IEEE 754 floating-point "single format" bitlayout, preserving Not-a-Number (NaN) values.

      Bit 31 (the bit that is selected by the mask0x80000000) represents the sign of the floating-pointnumber.Bits 30-23 (the bits that are selected by the mask0x7f800000) represent the exponent.Bits 22-0 (the bits that are selected by the mask0x007fffff) represent the significand (sometimes calledthe mantissa) of the floating-point number.

      If the argument is positive infinity, the result is0x7f800000.

      If the argument is negative infinity, the result is0xff800000.

      If the argument is NaN, the result is the integer representingthe actual NaN value. Unlike thefloatToIntBitsmethod,floatToRawIntBits does not collapse all thebit patterns encoding a NaN to a single "canonical"NaN value.

      In all cases, the result is an integer that, when given to theintBitsToFloat(int) method, will produce afloating-point value the same as the argument tofloatToRawIntBits.

      Parameters:
      value - a floating-point number.
      Returns:
      the bits that represent the floating-point number.
      Since:
      1.3
    • intBitsToFloat

      public static float intBitsToFloat(int bits)
      Returns thefloat value corresponding to a givenbit representation.The argument is considered to be a representation of afloating-point value according to the IEEE 754 floating-point"single format" bit layout.

      If the argument is0x7f800000, the result is positiveinfinity.

      If the argument is0xff800000, the result is negativeinfinity.

      If the argument is any value in the range0x7f800001 through0x7fffffff or inthe range0xff800001 through0xffffffff, the result is a NaN. No IEEE 754floating-point operation provided by Java can distinguishbetween two NaN values of the same type with different bitpatterns. Distinct values of NaN are only distinguishable byuse of theFloat.floatToRawIntBits method.

      In all other cases, lets,e, andm be threevalues that can be computed from the argument:

      int s = ((bits >> 31) == 0) ? 1 : -1;int e = ((bits >> 23) & 0xff);int m = (e == 0) ?                (bits & 0x7fffff) << 1 :                (bits & 0x7fffff) | 0x800000;
      Then the floating-point result equals the value of the mathematicalexpressions·m·2e-150.

      Note that this method may not be able to return afloat NaN with exactly same bit pattern as theint argument. IEEE 754 distinguishes between twokinds of NaNs, quiet NaNs andsignaling NaNs. Thedifferences between the two kinds of NaN are generally notvisible in Java. Arithmetic operations on signaling NaNs turnthem into quiet NaNs with a different, but often similar, bitpattern. However, on some processors merely copying asignaling NaN also performs that conversion. In particular,copying a signaling NaN to return it to the calling method mayperform this conversion. SointBitsToFloat maynot be able to return afloat with a signaling NaNbit pattern. Consequently, for someint values,floatToRawIntBits(intBitsToFloat(start)) maynot equalstart. Moreover, whichparticular bit patterns represent signaling NaNs is platformdependent; although all NaN bit patterns, quiet or signaling,must be in the NaN range identified above.

      Parameters:
      bits - an integer.
      Returns:
      thefloat floating-point value with the same bit pattern.
    • float16ToFloat

      public static float float16ToFloat(short floatBinary16)
      Returns thefloat value closest to the numerical valueof the argument, a floating-point binary16 value encoded in ashort. The conversion is exact; all binary16 values canbe exactly represented infloat.Special cases:
      • If the argument is zero, the result is a zero with thesame sign as the argument.
      • If the argument is infinite, the result is an infinitywith the same sign as the argument.
      • If the argument is a NaN, the result is a NaN.

      IEEE 754 binary16 format

      The IEEE 754 standard defines binary16 as a 16-bit format, alongwith the 32-bit binary32 format (corresponding to thefloat type) and the 64-bit binary64 format (corresponding tothedouble type). The binary16 format is similar to theother IEEE 754 formats, except smaller, having all the usualIEEE 754 values such as NaN, signed infinities, signed zeros,and subnormals. The parameters (JLS4.2.3) for thebinary16 format are N = 11 precision bits, K = 5 exponent bits,Emax = 15, andEmin = -14.
      API Note:
      This method corresponds to the convertFormat operation definedin IEEE 754 from the binary16 format to the binary32 format.The operation of this method is analogous to a primitivewidening conversion (JLS5.1.2).
      Parameters:
      floatBinary16 - the binary16 value to convert tofloat
      Returns:
      thefloat value closest to the numerical valueof the argument, a floating-point binary16 value encoded in ashort
      Since:
      20
    • floatToFloat16

      public static short floatToFloat16(float f)
      Returns the floating-point binary16 value, encoded in ashort, closest in value to the argument.The conversion is computed under theround to nearest even roundingmode.Special cases:
      • If the argument is zero, the result is a zero with thesame sign as the argument.
      • If the argument is infinite, the result is an infinitywith the same sign as the argument.
      • If the argument is a NaN, the result is a NaN.
      Thebinary16 format is discussed inmore detail in thefloat16ToFloat(short) method.
      API Note:
      This method corresponds to the convertFormat operation definedin IEEE 754 from the binary32 format to the binary16 format.The operation of this method is analogous to a primitivenarrowing conversion (JLS5.1.3).
      Parameters:
      f - thefloat value to convert to binary16
      Returns:
      the floating-point binary16 value, encoded in ashort, closest in value to the argument
      Since:
      20
    • compareTo

      public int compareTo(Float anotherFloat)
      Compares twoFloat objects numerically.This method imposes a total order onFloat objectswith two differences compared to the incomplete order defined bythe Java language numerical comparison operators (<, <=,==, >=, >) onfloat values.
      • A NaN isunordered with respect to other values and unequal to itself under the comparison operators. This method chooses to define Float.NaN to be equal to itself and greater than all otherdouble values (including Float.POSITIVE_INFINITY).
      • Positive zero and negative zero compare equal numerically, but are distinct and distinguishable values. This method chooses to define positive zero (+0.0f), to be greater than negative zero (-0.0f).
      This ensures that thenatural ordering ofFloatobjects imposed by this method isconsistent withequals; seethisdiscussion for details of floating-point comparison andordering.
      Specified by:
      compareTo in interface Comparable<Float>
      Parameters:
      anotherFloat - theFloat to be compared.
      Returns:
      the value0 ifanotherFloat is numerically equal to thisFloat; a value less than0 if thisFloat is numerically less thananotherFloat; and a value greater than0 if thisFloat is numerically greater thananotherFloat.
      SeeJava Language Specification:
      15.20.1 Numerical Comparison Operators<,<=,>, and>=
      Since:
      1.2
    • compare

      public static int compare(float f1, float f2)
      Compares the two specifiedfloat values. The signof the integer value returned is the same as that of theinteger that would be returned by the call:
         Float.valueOf(f1).compareTo(Float.valueOf(f2))
      Parameters:
      f1 - the firstfloat to compare.
      f2 - the secondfloat to compare.
      Returns:
      the value0 iff1 is numerically equal tof2; a value less than0 iff1 is numerically less thanf2; and a value greater than0 iff1 is numerically greater thanf2.
      Since:
      1.4
    • sum

      public static float sum(float a, float b)
      Adds twofloat values together as per the + operator.
      API Note:
      This method corresponds to the addition operationdefined in IEEE 754.
      Parameters:
      a - the first operand
      b - the second operand
      Returns:
      the sum ofa andb
      SeeJava Language Specification:
      4.2.4 Floating-Point Operations
      Since:
      1.8
      See Also:
    • max

      public static float max(float a, float b)
      Returns the greater of twofloat valuesas if by callingMath.max.
      API Note:
      This method corresponds to the maximum operation defined inIEEE 754.
      Parameters:
      a - the first operand
      b - the second operand
      Returns:
      the greater ofa andb
      Since:
      1.8
      See Also:
    • min

      public static float min(float a, float b)
      Returns the smaller of twofloat valuesas if by callingMath.min.
      API Note:
      This method corresponds to the minimum operation defined inIEEE 754.
      Parameters:
      a - the first operand
      b - the second operand
      Returns:
      the smaller ofa andb
      Since:
      1.8
      See Also:
    • describeConstable

      public Optional<Float> describeConstable()
      Returns anOptional containing the nominal descriptor for thisinstance, which is the instance itself.
      Specified by:
      describeConstable in interface Constable
      Returns:
      anOptional describing theFloat instance
      Since:
      12
    • resolveConstantDesc

      public Float resolveConstantDesc(MethodHandles.Lookup lookup)
      Resolves this instance as aConstantDesc, the result of which isthe instance itself.
      Specified by:
      resolveConstantDesc in interface ConstantDesc
      Parameters:
      lookup - ignored
      Returns:
      theFloat instance
      Since:
      12