1 /* Float.java -- object wrapper for float
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
43 * Instances of class <code>Float</code> represent primitive
44 * <code>float</code> values.
46 * Additionally, this class provides various helper functions and variables
50 * @author Andrew Haley (aph@cygnus.com)
51 * @author Eric Blake (ebb9@email.byu.edu)
52 * @author Tom Tromey (tromey@redhat.com)
53 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
55 * @status partly updated to 1.5
57 public final class Float
extends Number
implements Comparable
<Float
>
60 * Compatible with JDK 1.0+.
62 private static final long serialVersionUID
= -2671257302660747028L;
65 * The maximum positive value a <code>double</code> may represent
68 public static final float MAX_VALUE
= 3.4028235e+38f
;
71 * The minimum positive value a <code>float</code> may represent
74 public static final float MIN_VALUE
= 1.4e-45f
;
77 * The value of a float representation -1.0/0.0, negative infinity.
79 public static final float NEGATIVE_INFINITY
= -1.0f
/ 0.0f
;
82 * The value of a float representation 1.0/0.0, positive infinity.
84 public static final float POSITIVE_INFINITY
= 1.0f
/ 0.0f
;
87 * All IEEE 754 values of NaN have the same value in Java.
89 public static final float NaN
= 0.0f
/ 0.0f
;
92 * The primitive type <code>float</code> is represented by this
93 * <code>Class</code> object.
96 public static final Class
<Float
> TYPE
= (Class
<Float
>) VMClassLoader
.getPrimitiveClass('F');
99 * The number of bits needed to represent a <code>float</code>.
102 public static final int SIZE
= 32;
105 * The immutable value of this Float.
107 * @serial the wrapped float
109 private final float value
;
112 * Create a <code>Float</code> from the primitive <code>float</code>
115 * @param value the <code>float</code> argument
117 public Float(float value
)
123 * Create a <code>Float</code> from the primitive <code>double</code>
126 * @param value the <code>double</code> argument
128 public Float(double value
)
130 this.value
= (float) value
;
134 * Create a <code>Float</code> from the specified <code>String</code>.
135 * This method calls <code>Float.parseFloat()</code>.
137 * @param s the <code>String</code> to convert
138 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
140 * @throws NullPointerException if <code>s</code> is null
141 * @see #parseFloat(String)
143 public Float(String s
)
145 value
= parseFloat(s
);
149 * Convert the <code>float</code> to a <code>String</code>.
150 * Floating-point string representation is fairly complex: here is a
151 * rundown of the possible values. "<code>[-]</code>" indicates that a
152 * negative sign will be printed if the value (or exponent) is negative.
153 * "<code><number></code>" means a string of digits ('0' to '9').
154 * "<code><digit></code>" means a single digit ('0' to '9').<br>
157 * <tr><th>Value of Float</th><th>String Representation</th></tr>
158 * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
159 * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
160 * <td><code>[-]number.number</code></td></tr>
161 * <tr><td>Other numeric value</td>
162 * <td><code>[-]<digit>.<number>
163 * E[-]<number></code></td></tr>
164 * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
165 * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
168 * Yes, negative zero <em>is</em> a possible value. Note that there is
169 * <em>always</em> a <code>.</code> and at least one digit printed after
170 * it: even if the number is 3, it will be printed as <code>3.0</code>.
171 * After the ".", all digits will be printed except trailing zeros. The
172 * result is rounded to the shortest decimal number which will parse back
175 * <p>To create other output formats, use {@link java.text.NumberFormat}.
177 * @XXX specify where we are not in accord with the spec.
179 * @param f the <code>float</code> to convert
180 * @return the <code>String</code> representing the <code>float</code>
182 public static String
toString(float f
)
184 return VMDouble
.toString(f
, true);
188 * Convert a float value to a hexadecimal string. This converts as
191 * <li> A NaN value is converted to the string "NaN".
192 * <li> Positive infinity is converted to the string "Infinity".
193 * <li> Negative infinity is converted to the string "-Infinity".
194 * <li> For all other values, the first character of the result is '-'
195 * if the value is negative. This is followed by '0x1.' if the
196 * value is normal, and '0x0.' if the value is denormal. This is
197 * then followed by a (lower-case) hexadecimal representation of the
198 * mantissa, with leading zeros as required for denormal values.
199 * The next character is a 'p', and this is followed by a decimal
200 * representation of the unbiased exponent.
202 * @param f the float value
203 * @return the hexadecimal string representation
206 public static String
toHexString(float f
)
211 return f
< 0 ?
"-Infinity" : "Infinity";
213 int bits
= floatToIntBits(f
);
214 StringBuilder result
= new StringBuilder();
220 final int mantissaBits
= 23;
221 final int exponentBits
= 8;
222 int mantMask
= (1 << mantissaBits
) - 1;
223 int mantissa
= bits
& mantMask
;
224 int expMask
= (1 << exponentBits
) - 1;
225 int exponent
= (bits
>>> mantissaBits
) & expMask
;
227 result
.append(exponent
== 0 ?
'0' : '1');
229 // For Float only, we have to adjust the mantissa.
231 result
.append(Integer
.toHexString(mantissa
));
232 if (exponent
== 0 && mantissa
!= 0)
234 // Treat denormal specially by inserting '0's to make
235 // the length come out right. The constants here are
236 // to account for things like the '0x'.
237 int offset
= 4 + ((bits
< 0) ?
1 : 0);
238 // The silly +3 is here to keep the code the same between
239 // the Float and Double cases. In Float the value is
240 // not a multiple of 4.
241 int desiredLength
= offset
+ (mantissaBits
+ 3) / 4;
242 while (result
.length() < desiredLength
)
243 result
.insert(offset
, '0');
246 if (exponent
== 0 && mantissa
== 0)
248 // Zero, so do nothing special.
253 boolean denormal
= exponent
== 0;
254 exponent
-= (1 << (exponentBits
- 1)) - 1;
260 result
.append(Integer
.toString(exponent
));
261 return result
.toString();
265 * Creates a new <code>Float</code> object using the <code>String</code>.
267 * @param s the <code>String</code> to convert
268 * @return the new <code>Float</code>
269 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
271 * @throws NullPointerException if <code>s</code> is null
272 * @see #parseFloat(String)
274 public static Float
valueOf(String s
)
276 return new Float(parseFloat(s
));
280 * Returns a <code>Float</code> object wrapping the value.
281 * In contrast to the <code>Float</code> constructor, this method
282 * may cache some values. It is used by boxing conversion.
284 * @param val the value to wrap
285 * @return the <code>Float</code>
288 public static Float
valueOf(float val
)
290 // We don't actually cache, but we could.
291 return new Float(val
);
295 * Parse the specified <code>String</code> as a <code>float</code>. The
296 * extended BNF grammar is as follows:<br>
298 * <em>DecodableString</em>:
299 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
300 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
301 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
302 * [ <code>f</code> | <code>F</code> | <code>d</code>
303 * | <code>D</code>] )
304 * <em>FloatingPoint</em>:
305 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
306 * [ <em>Exponent</em> ] )
307 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
309 * ( ( <code>e</code> | <code>E</code> )
310 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
311 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
314 * <p>NaN and infinity are special cases, to allow parsing of the output
315 * of toString. Otherwise, the result is determined by calculating
316 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
317 * to the nearest float. Remember that many numbers cannot be precisely
318 * represented in floating point. In case of overflow, infinity is used,
319 * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
320 * this does not accept Unicode digits outside the ASCII range.
322 * <p>If an unexpected character is found in the <code>String</code>, a
323 * <code>NumberFormatException</code> will be thrown. Leading and trailing
324 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
325 * internal to the actual number are not allowed.
327 * <p>To parse numbers according to another format, consider using
328 * {@link java.text.NumberFormat}.
330 * @XXX specify where/how we are not in accord with the spec.
332 * @param str the <code>String</code> to convert
333 * @return the <code>float</code> value of <code>s</code>
334 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
336 * @throws NullPointerException if <code>s</code> is null
339 * @see #POSITIVE_INFINITY
340 * @see #NEGATIVE_INFINITY
343 public static float parseFloat(String str
)
345 // XXX Rounding parseDouble() causes some errors greater than 1 ulp from
346 // the infinitely precise decimal.
347 return (float) Double
.parseDouble(str
);
351 * Return <code>true</code> if the <code>float</code> has the same
352 * value as <code>NaN</code>, otherwise return <code>false</code>.
354 * @param v the <code>float</code> to compare
355 * @return whether the argument is <code>NaN</code>
357 public static boolean isNaN(float v
)
359 // This works since NaN != NaN is the only reflexive inequality
360 // comparison which returns true.
365 * Return <code>true</code> if the <code>float</code> has a value
366 * equal to either <code>NEGATIVE_INFINITY</code> or
367 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
369 * @param v the <code>float</code> to compare
370 * @return whether the argument is (-/+) infinity
372 public static boolean isInfinite(float v
)
374 return v
== POSITIVE_INFINITY
|| v
== NEGATIVE_INFINITY
;
378 * Return <code>true</code> if the value of this <code>Float</code>
379 * is the same as <code>NaN</code>, otherwise return <code>false</code>.
381 * @return whether this <code>Float</code> is <code>NaN</code>
383 public boolean isNaN()
389 * Return <code>true</code> if the value of this <code>Float</code>
390 * is the same as <code>NEGATIVE_INFINITY</code> or
391 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
393 * @return whether this <code>Float</code> is (-/+) infinity
395 public boolean isInfinite()
397 return isInfinite(value
);
401 * Convert the <code>float</code> value of this <code>Float</code>
402 * to a <code>String</code>. This method calls
403 * <code>Float.toString(float)</code> to do its dirty work.
405 * @return the <code>String</code> representation
406 * @see #toString(float)
408 public String
toString()
410 return toString(value
);
414 * Return the value of this <code>Float</code> as a <code>byte</code>.
416 * @return the byte value
419 public byte byteValue()
425 * Return the value of this <code>Float</code> as a <code>short</code>.
427 * @return the short value
430 public short shortValue()
432 return (short) value
;
436 * Return the value of this <code>Integer</code> as an <code>int</code>.
438 * @return the int value
440 public int intValue()
446 * Return the value of this <code>Integer</code> as a <code>long</code>.
448 * @return the long value
450 public long longValue()
456 * Return the value of this <code>Float</code>.
458 * @return the float value
460 public float floatValue()
466 * Return the value of this <code>Float</code> as a <code>double</code>
468 * @return the double value
470 public double doubleValue()
476 * Return a hashcode representing this Object. <code>Float</code>'s hash
477 * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
479 * @return this Object's hash code
480 * @see #floatToIntBits(float)
482 public int hashCode()
484 return floatToIntBits(value
);
488 * Returns <code>true</code> if <code>obj</code> is an instance of
489 * <code>Float</code> and represents the same float value. Unlike comparing
490 * two floats with <code>==</code>, this treats two instances of
491 * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
492 * <code>-0.0</code> as unequal.
494 * <p>Note that <code>f1.equals(f2)</code> is identical to
495 * <code>floatToIntBits(f1.floatValue()) ==
496 * floatToIntBits(f2.floatValue())</code>.
498 * @param obj the object to compare
499 * @return whether the objects are semantically equal
501 public boolean equals(Object obj
)
503 if (! (obj
instanceof Float
))
506 float f
= ((Float
) obj
).value
;
508 // Avoid call to native method. However, some implementations, like gcj,
509 // are better off using floatToIntBits(value) == floatToIntBits(f).
510 // Check common case first, then check NaN and 0.
512 return (value
!= 0) || (1 / value
== 1 / f
);
513 return isNaN(value
) && isNaN(f
);
517 * Convert the float to the IEEE 754 floating-point "single format" bit
518 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
519 * (masked by 0x7f800000) represent the exponent, and bits 22-0
520 * (masked by 0x007fffff) are the mantissa. This function collapses all
521 * versions of NaN to 0x7fc00000. The result of this function can be used
522 * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
523 * original <code>float</code> value.
525 * @param value the <code>float</code> to convert
526 * @return the bits of the <code>float</code>
527 * @see #intBitsToFloat(int)
529 public static int floatToIntBits(float value
)
531 return VMFloat
.floatToIntBits(value
);
535 * Convert the float to the IEEE 754 floating-point "single format" bit
536 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
537 * (masked by 0x7f800000) represent the exponent, and bits 22-0
538 * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
539 * rather than collapsing to a canonical value. The result of this function
540 * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
541 * obtain the original <code>float</code> value.
543 * @param value the <code>float</code> to convert
544 * @return the bits of the <code>float</code>
545 * @see #intBitsToFloat(int)
547 public static int floatToRawIntBits(float value
)
549 return VMFloat
.floatToRawIntBits(value
);
553 * Convert the argument in IEEE 754 floating-point "single format" bit
554 * layout to the corresponding float. Bit 31 (the most significant) is the
555 * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
556 * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
557 * NaN alone, so that you can recover the bit pattern with
558 * <code>Float.floatToRawIntBits(float)</code>.
560 * @param bits the bits to convert
561 * @return the <code>float</code> represented by the bits
562 * @see #floatToIntBits(float)
563 * @see #floatToRawIntBits(float)
565 public static float intBitsToFloat(int bits
)
567 return VMFloat
.intBitsToFloat(bits
);
571 * Compare two Floats numerically by comparing their <code>float</code>
572 * values. The result is positive if the first is greater, negative if the
573 * second is greater, and 0 if the two are equal. However, this special
574 * cases NaN and signed zero as follows: NaN is considered greater than
575 * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
576 * zero is considered greater than negative zero.
578 * @param f the Float to compare
579 * @return the comparison
582 public int compareTo(Float f
)
584 return compare(value
, f
.value
);
588 * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
589 * other words this compares two floats, special casing NaN and zero,
590 * without the overhead of objects.
592 * @param x the first float to compare
593 * @param y the second float to compare
594 * @return the comparison
597 public static int compare(float x
, float y
)
600 return isNaN(y
) ?
0 : 1;
603 // recall that 0.0 == -0.0, so we convert to infinities and try again
604 if (x
== 0 && y
== 0)
605 return (int) (1 / x
- 1 / y
);
609 return x
> y ?
1 : -1;