Class Float
- All Implemented Interfaces:
Serializable,Comparable<Float>,Constable,ConstantDesc
Float 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
FieldsModifier and TypeFieldDescriptionstatic final intThe number of bytes used to represent afloatvalue,4.static final intMaximum exponent a finitefloatvariable may have,127.static final floatA constant holding the largest positive finite value of typefloat, (2-2-23)·2127.static final intMinimum exponent a normalizedfloatvariable may have,-126.static final floatA constant holding the smallest positive normal value of typefloat, 2-126.static final floatA constant holding the smallest positive nonzero value of typefloat, 2-149.static final floatA constant holding a Not-a-Number (NaN) value of typefloat.static final floatA constant holding the negative infinity of typefloat.static final floatA constant holding the positive infinity of typefloat.static final intThe number of bits in the significand of afloatvalue,24.static final intThe number of bits used to represent afloatvalue,32.TheClassinstance representing the primitive typefloat.Constructor Summary
ConstructorsMethod Summary
Modifier and TypeMethodDescriptionbyteReturns the value of thisFloatas abyteaftera narrowing primitive conversion.static intcompare(float f1, float f2) Compares the two specifiedfloatvalues.intCompares twoFloatobjects numerically.Returns anOptionalcontaining the nominal descriptor for thisinstance, which is the instance itself.doubleReturns the value of thisFloatas adoubleafter a widening primitive conversion.booleanCompares this object against the specified object.static floatfloat16ToFloat(short floatBinary16) Returns thefloatvalue closest to the numerical valueof the argument, a floating-point binary16 value encoded in ashort.static shortfloatToFloat16(float f) Returns the floating-point binary16 value, encoded in ashort, closest in value to the argument.static intfloatToIntBits(float value) Returns a representation of the specified floating-point valueaccording to the IEEE 754 floating-point "single format" bitlayout.static intfloatToRawIntBits(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.floatReturns thefloatvalue of thisFloatobject.inthashCode()Returns a hash code for thisFloatobject.static inthashCode(float value) Returns a hash code for afloatvalue; compatible withFloat.hashCode().static floatintBitsToFloat(int bits) Returns thefloatvalue corresponding to a givenbit representation.intintValue()Returns the value of thisFloatas anintaftera narrowing primitive conversion.static booleanisFinite(float f) Returnstrueif the argument is a finite floating-pointvalue; returnsfalseotherwise (for NaN and infinityarguments).booleanReturnstrueif thisFloatvalue isinfinitely large in magnitude,falseotherwise.static booleanisInfinite(float v) Returnstrueif the specified number is infinitelylarge in magnitude,falseotherwise.booleanisNaN()Returnstrueif thisFloatvalue is aNot-a-Number (NaN),falseotherwise.static booleanisNaN(float v) Returnstrueif the specified number is aNot-a-Number (NaN) value,falseotherwise.longReturns value of thisFloatas alongafter anarrowing primitive conversion.static floatmax(float a, float b) Returns the greater of twofloatvaluesas if by callingMath.max.static floatmin(float a, float b) Returns the smaller of twofloatvaluesas if by callingMath.min.static floatparseFloat(String s) Returns a newfloatinitialized to the valuerepresented by the specifiedString, as performedby thevalueOfmethod of classFloat.Resolves this instance as aConstantDesc, the result of which isthe instance itself.shortReturns the value of thisFloatas ashortafter a narrowing primitive conversion.static floatsum(float a, float b) Adds twofloatvalues together as per the + operator.staticStringtoHexString(float f) Returns a hexadecimal string representation of thefloatargument.toString()Returns a string representation of thisFloatobject.staticStringtoString(float f) Returns a string representation of thefloatargument.staticFloatvalueOf(float f) Returns aFloatinstance representing the specifiedfloatvalue.staticFloatReturns aFloatobject holding thefloatvalue represented by the argument strings.
Field Details
POSITIVE_INFINITY
public static final float POSITIVE_INFINITYA 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_INFINITYA constant holding the negative infinity of typefloat. It is equal to the value returned byFloat.intBitsToFloat(0xff800000).- See Also:
NaN
public static final float NaNA 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_VALUEA constant holding the largest positive finite value of typefloat, (2-2-23)·2127.It is equal to the hexadecimal floating-point literal0x1.fffffeP+127fand also equal toFloat.intBitsToFloat(0x7f7fffff).- See Also:
MIN_NORMAL
public static final float MIN_NORMALA constant holding the smallest positive normal value of typefloat, 2-126. It is equal to thehexadecimal floating-point literal0x1.0p-126fand alsoequal toFloat.intBitsToFloat(0x00800000).- Since:
- 1.6
- See Also:
MIN_VALUE
public static final float MIN_VALUEA 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 SIZEThe number of bits used to represent afloatvalue,32.- Since:
- 1.5
- See Also:
PRECISION
public static final int PRECISIONThe number of bits in the significand of afloatvalue,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_EXPONENTMaximum exponent a finitefloatvariable 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_EXPONENTMinimum exponent a normalizedfloatvariable 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 BYTESThe number of bytes used to represent afloatvalue,4.- Since:
- 1.8
- See Also:
TYPE
Constructor Details
Float
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 allocatedFloatobject thatrepresents the primitivefloatargument.- Parameters:
value- the value to be represented by theFloat.
Float
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 allocatedFloatobject thatrepresents the argument converted to typefloat.- Parameters:
value- the value to be represented by theFloat.
Float
Deprecated.It is rarely appropriate to use this constructor.UseparseFloat(String)to convert a string to afloatprimitive, or usevalueOf(String)to convert a string to aFloatobject.Constructs a newly allocatedFloatobject thatrepresents the floating-point value of typefloatrepresented by the string. The string is converted to afloatvalue as if by thevalueOfmethod.- Parameters:
s- a string to be converted to aFloat.- Throws:
NumberFormatException- if the string does not contain a parsable number.
Method Details
toString
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.
- Ifm is infinity, it is represented by the characters
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-1 ≤s < 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 lets1…snbe 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 as
0.0…0s1…sn,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 ass1…sn
0…0.0,where there are exactlyi zeroesbetweensn and the decimal point.For example, 123 × 102 is formatted as12300.0. - Subcasei < 0:dm is formatted ass1…sn+i
.sn+i+1…sn,where there are exactly -i digits to the right ofthe decimal point.For example, 123 × 10-1 is formatted as12.3.
- Subcasei ≥ 0:dm is formatted ass1…sn
- Casee < -3 ore ≥ 7:computerized scientific notation is used to formatdm.Heree is formatted as by
Integer.toString(int).- Subcasen = 1:dm is formatted ass1
.0Ee.For example, 1 × 1023 is formatted as1.0E23. - Subcasen > 1:dm is formatted ass1
.s2…snEe.For example, 123 × 10-21 is formatted as1.23E-19.
- Subcasen = 1:dm is formatted ass1
To create localized string representations of a floating-pointvalue, use subclasses of
NumberFormat.- 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 the
floatto aBigDecimalexactly and then rounding theBigDecimaltothe 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- thefloatto be converted.- Returns:
- a string representation of the argument.
- If the argument is NaN, the result is the string"
toHexString
Returns a hexadecimal string representation of thefloatargument. 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 a
floatvalue 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.toStringon theexponent value. - Ifm is a
floatvalue 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.
- Ifm is infinity, it is represented by the string
Examples Floating-point Value Hexadecimal String 1.00x1.0p0-1.0-0x1.0p02.00x1.0p13.00x1.8p10.50x1.0p-10.250x1.0p-2Float.MAX_VALUE0x1.fffffep127Minimum Normal Value0x1.0p-126Maximum Subnormal Value0x0.fffffep-126Float.MIN_VALUE0x0.000002p-126- API Note:
- This method corresponds to the convertToHexCharacter operationdefined in IEEE 754.
- Parameters:
f- thefloatto be converted.- Returns:
- a hex string representation of the argument.
- Since:
- 1.5
- If the argument is NaN, the result is the string "
valueOf
Returns aFloatobject holding thefloatvalue represented by the argument strings.If
sisnull, then aNullPointerExceptionis thrown.Leading and trailing whitespace characters in
sare ignored. Whitespace is removed as if by theString.trim()method; that is, both ASCII space and controlcharacters are removed. The rest ofsshouldconstitute aFloatValue as described by the lexicalsyntax rules:
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.If- FloatValue:
- Signopt
NaN- Signopt
Infinity- Signopt FloatingPointLiteral
- Signopt HexFloatingPointLiteral
- SignedInteger
- Signopt
- HexFloatingPointLiteral:
- HexSignificand BinaryExponent FloatTypeSuffixopt
- HexSignificand:
- HexNumeral
- HexNumeral
.0xHexDigitsopt.HexDigits0XHexDigitsopt.HexDigits - HexNumeral
- BinaryExponent:
- BinaryExponentIndicator SignedInteger
- BinaryExponentIndicator:
pP
sdoes not have the form ofaFloatValue, then aNumberFormatExceptionis thrown. Otherwise,sis 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 ofsis largeenough in magnitude (greater than or equal to (MAX_VALUE+ulp(MAX_VALUE)/2),rounding tofloatwill result in an infinity and if theexact value ofsis small enough in magnitude (lessthan or equal toMIN_VALUE/2), rounding to float willresult in a zero.Finally, after rounding aFloatobject representingthisfloatvalue is returned.Note that trailing format specifiers, specifiers thatdetermine the type of a floating-point literal(
1.0fis afloatvalue;1.0dis adoublevalue), 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 bydoubletofloat, isnot equivalent to converting a string directly tofloat. For example, if first converted to anintermediatedoubleand then tofloat, the string"1.00000017881393421514957253748434595763683319091796875001d"
results in thefloatvalue1.0000002f; if the string is converted directly tofloat,1.0000001fresults.To avoid calling this method on an invalid string and havinga
NumberFormatExceptionbe thrown, the documentationforDouble.valueOflists 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, use
NumberFormat. Forexample,whereNumberFormat.getInstance(l).parse(s).floatValue();lis the desired locale, orLocale.ROOTif locale insensitive., This method corresponds to the convertFromDecimalCharacter andconvertFromHexCharacter operations defined in IEEE 754. - Parameters:
s- the string to be parsed.- Returns:
- a
Floatobject holding the value represented by theStringargument. - Throws:
NumberFormatException- if the string does not contain a parsable number.- See Also:
valueOf
Returns aFloatinstance representing the specifiedfloatvalue.If a newFloatinstance 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:
- a
Floatinstance representingf. - Since:
- 1.5
parseFloat
Returns a newfloatinitialized to the valuerepresented by the specifiedString, as performedby thevalueOfmethod of classFloat.- Parameters:
s- the string to be parsed.- Returns:
- the
floatvalue represented by the string argument. - Throws:
NullPointerException- if the string is nullNumberFormatException- if the string does not contain a parsablefloat.- Since:
- 1.2
- See Also:
isNaN
public static boolean isNaN(float v) Returnstrueif the specified number is aNot-a-Number (NaN) value,falseotherwise.- API Note:
- This method corresponds to the isNaN operation defined in IEEE754.
- Parameters:
v- the value to be tested.- Returns:
trueif the argument is NaN;falseotherwise.
isInfinite
public static boolean isInfinite(float v) Returnstrueif the specified number is infinitelylarge in magnitude,falseotherwise.- API Note:
- This method corresponds to the isInfinite operation defined inIEEE 754.
- Parameters:
v- the value to be tested.- Returns:
trueif the argument is positive infinity or negative infinity;falseotherwise.
isFinite
public static boolean isFinite(float f) Returnstrueif the argument is a finite floating-pointvalue; returnsfalseotherwise (for NaN and infinityarguments).- API Note:
- This method corresponds to the isFinite operation defined inIEEE 754.
- Parameters:
f- thefloatvalue to be tested- Returns:
trueif the argument is a finitefloating-point value,falseotherwise.- Since:
- 1.8
isNaN
public boolean isNaN()Returnstrueif thisFloatvalue is aNot-a-Number (NaN),falseotherwise.- Returns:
trueif the value represented by this object is NaN;falseotherwise.
isInfinite
public boolean isInfinite()Returnstrueif thisFloatvalue isinfinitely large in magnitude,falseotherwise.- Returns:
trueif the value represented by this object is positive infinity or negative infinity;falseotherwise.
toString
byteValue
public byte byteValue()Returns the value of thisFloatas abyteaftera narrowing primitive conversion.- Overrides:
byteValuein classNumber- Returns:
- the
floatvalue represented by this object converted to typebyte - SeeJava Language Specification:
- 5.1.3 Narrowing Primitive Conversion
shortValue
public short shortValue()Returns the value of thisFloatas ashortafter a narrowing primitive conversion.- Overrides:
shortValuein classNumber- Returns:
- the
floatvalue 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 thisFloatas anintaftera narrowing primitive conversion.- Specified by:
intValuein classNumber- API Note:
- This method corresponds to the convertToIntegerTowardZerooperation defined in IEEE 754.
- Returns:
- the
floatvalue represented by this object converted to typeint - SeeJava Language Specification:
- 5.1.3 Narrowing Primitive Conversion
longValue
public long longValue()Returns value of thisFloatas alongafter anarrowing primitive conversion.- Specified by:
longValuein classNumber- API Note:
- This method corresponds to the convertToIntegerTowardZerooperation defined in IEEE 754.
- Returns:
- the
floatvalue represented by this object converted to typelong - SeeJava Language Specification:
- 5.1.3 Narrowing Primitive Conversion
floatValue
public float floatValue()Returns thefloatvalue of thisFloatobject.- Specified by:
floatValuein classNumber- Returns:
- the
floatvalue represented by this object
doubleValue
public double doubleValue()Returns the value of thisFloatas adoubleafter a widening primitive conversion.- Specified by:
doubleValuein classNumber- API Note:
- This method corresponds to the convertFormat operation definedin IEEE 754.
- Returns:
- the
floatvalue 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 thisFloatobject. Theresult is the integer bit representation, exactly as producedby the methodfloatToIntBits(float), of the primitivefloatvalue represented by thisFloatobject.hashCode
public static int hashCode(float value) Returns a hash code for afloatvalue; compatible withFloat.hashCode().- Parameters:
value- the value to hash- Returns:
- a hash code value for a
floatvalue. - Since:
- 1.8
equals
Compares this object against the specified object. The resultistrueif and only if the argument is notnulland is aFloatobject thatrepresents afloatwith the same value as thefloatrepresented by this object. For thispurpose, twofloatvalues are considered to be thesame if and only if the methodfloatToIntBits(float)returns the identicalintvalue when applied toeach.- Overrides:
equalsin classObject- API Note:
- This method is defined in terms of
floatToIntBits(float)rather than the==operator onfloatvalues 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:
trueif the objects are the same;falseotherwise.- 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 mask
0x80000000) 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 is
0x7f800000.If the argument is negative infinity, the result is
0xff800000.If the argument is NaN, the result is
0x7fc00000.In all cases, the result is an integer that, when given to the
intBitsToFloat(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 mask
0x80000000) 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 is
0x7f800000.If the argument is negative infinity, the result is
0xff800000.If the argument is NaN, the result is the integer representingthe actual NaN value. Unlike the
floatToIntBitsmethod,floatToRawIntBitsdoes 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 the
intBitsToFloat(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 thefloatvalue 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 is
0x7f800000, the result is positiveinfinity.If the argument is
0xff800000, the result is negativeinfinity.If the argument is any value in the range
0x7f800001through0x7fffffffor inthe range0xff800001through0xffffffff, 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.floatToRawIntBitsmethod.In all other cases, lets,e, andm be threevalues that can be computed from the argument:
Then the floating-point result equals the value of the mathematicalexpressions·m·2e-150.int s = ((bits >> 31) == 0) ? 1 : -1;int e = ((bits >> 23) & 0xff);int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000;Note that this method may not be able to return a
floatNaN with exactly same bit pattern as theintargument. 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. SointBitsToFloatmaynot be able to return afloatwith a signaling NaNbit pattern. Consequently, for someintvalues,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:
- the
floatfloating-point value with the same bit pattern.
float16ToFloat
public static float float16ToFloat(short floatBinary16) Returns thefloatvalue 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 thefloattype) and the 64-bit binary64 format (corresponding tothedoubletype). 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:
- the
floatvalue 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.
float16ToFloat(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- thefloatvalue to convert to binary16- Returns:
- the floating-point binary16 value, encoded in a
short, closest in value to the argument - Since:
- 20
compareTo
Compares twoFloatobjects numerically.This method imposes a total order onFloatobjectswith two differences compared to the incomplete order defined bythe Java language numerical comparison operators (<, <=,==, >=, >) onfloatvalues.- A NaN isunordered with respect to other values and unequal to itself under the comparison operators. This method chooses to define
Float.NaNto be equal to itself and greater than all otherdoublevalues (includingFloat.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).
Floatobjects imposed by this method isconsistent withequals; seethisdiscussion for details of floating-point comparison andordering.- Specified by:
compareToin interfaceComparable<Float>- Parameters:
anotherFloat- theFloatto be compared.- Returns:
- the value
0ifanotherFloatis numerically equal to thisFloat; a value less than0if thisFloatis numerically less thananotherFloat; and a value greater than0if thisFloatis numerically greater thananotherFloat. - SeeJava Language Specification:
- 15.20.1 Numerical Comparison Operators
<,<=,>, and>= - Since:
- 1.2
- A NaN isunordered with respect to other values and unequal to itself under the comparison operators. This method chooses to define
compare
public static int compare(float f1, float f2) Compares the two specifiedfloatvalues. 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 firstfloatto compare.f2- the secondfloatto compare.- Returns:
- the value
0iff1is numerically equal tof2; a value less than0iff1is numerically less thanf2; and a value greater than0iff1is numerically greater thanf2. - Since:
- 1.4
sum
public static float sum(float a, float b) Adds twofloatvalues together as per the + operator.- API Note:
- This method corresponds to the addition operationdefined in IEEE 754.
- Parameters:
a- the first operandb- the second operand- Returns:
- the sum of
aandb - 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 twofloatvaluesas if by callingMath.max.- API Note:
- This method corresponds to the maximum operation defined inIEEE 754.
- Parameters:
a- the first operandb- the second operand- Returns:
- the greater of
aandb - Since:
- 1.8
- See Also:
min
public static float min(float a, float b) Returns the smaller of twofloatvaluesas if by callingMath.min.- API Note:
- This method corresponds to the minimum operation defined inIEEE 754.
- Parameters:
a- the first operandb- the second operand- Returns:
- the smaller of
aandb - Since:
- 1.8
- See Also:
describeConstable
resolveConstantDesc
Resolves this instance as aConstantDesc, the result of which isthe instance itself.- Specified by:
resolveConstantDescin interfaceConstantDesc- Parameters:
lookup- ignored- Returns:
- theFloat instance
- Since:
- 12