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. */
40 * Instances of class <code>Float</code> represent primitive <code>float</code>
43 * Additionally, this class provides various helper functions and variables
47 * @author Andrew Haley (aph@cygnus.com)
48 * @author Eric Blake (ebb9@email.byu.edu)
49 * @author Tom Tromey (tromey@redhat.com)
50 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
52 * @status partly updated to 1.5
54 public final class Float {
56 * Compatible with JDK 1.0+.
58 private static final long serialVersionUID = -2671257302660747028L;
61 * The maximum positive value a <code>double</code> may represent is
64 public static final float MAX_VALUE = 3.4028235e+38f;
67 * The minimum positive value a <code>float</code> may represent is 1.4e-45.
69 public static final float MIN_VALUE = 1.4e-45f;
72 * The value of a float representation -1.0/0.0, negative infinity.
74 public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
77 * The value of a float representation 1.0/0.0, positive infinity.
79 public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
82 * All IEEE 754 values of NaN have the same value in Java.
84 public static final float NaN = 0.0f / 0.0f;
87 * The primitive type <code>float</code> is represented by this
88 * <code>Class</code> object.
92 // public static final Class<Float> TYPE = (Class<Float>)
93 // VMClassLoader.getPrimitiveClass('F');
96 * The number of bits needed to represent a <code>float</code>.
100 public static final int SIZE = 32;
103 * Cache representation of 0
105 private static final Float ZERO = new Float(0.0f);
108 * Cache representation of 1
110 private static final Float ONE = new Float(1.0f);
113 * The immutable value of this Float.
115 * @serial the wrapped float
117 private final float value;
120 * Create a <code>Float</code> from the primitive <code>float</code>
124 * the <code>float</code> argument
126 public Float(float value) {
131 * Create a <code>Float</code> from the primitive <code>double</code>
135 * the <code>double</code> argument
137 public Float(double value) {
138 this.value = (float) value;
142 * Create a <code>Float</code> from the specified <code>String</code>. This
143 * method calls <code>Float.parseFloat()</code>.
146 * the <code>String</code> to convert
147 * @throws NumberFormatException
148 * if <code>s</code> cannot be parsed as a <code>float</code>
149 * @throws NullPointerException
150 * if <code>s</code> is null
151 * @see #parseFloat(String)
153 public Float(String s) {
154 value = parseFloat(s);
158 * Convert the <code>float</code> to a <code>String</code>. Floating-point
159 * string representation is fairly complex: here is a rundown of the possible
160 * values. "<code>[-]</code>" indicates that a negative sign will be printed
161 * if the value (or exponent) is negative. "<code><number></code>" means
162 * a string of digits ('0' to '9'). "<code><digit></code>" means a
163 * single digit ('0' to '9').<br>
167 * <th>Value of Float</th>
168 * <th>String Representation</th>
172 * <td><code>[-]0.0</code></td>
175 * <td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
176 * <td><code>[-]number.number</code></td>
179 * <td>Other numeric value</td>
180 * <td><code>[-]<digit>.<number>
181 * E[-]<number></code></td>
184 * <td>[+-] infinity</td>
185 * <td><code>[-]Infinity</code></td>
189 * <td><code>NaN</code></td>
193 * Yes, negative zero <em>is</em> a possible value. Note that there is
194 * <em>always</em> a <code>.</code> and at least one digit printed after it:
195 * even if the number is 3, it will be printed as <code>3.0</code>. After the
196 * ".", all digits will be printed except trailing zeros. The result is
197 * rounded to the shortest decimal number which will parse back to the same
201 * To create other output formats, use {@link java.text.NumberFormat}.
203 * @XXX specify where we are not in accord with the spec.
206 * the <code>float</code> to convert
207 * @return the <code>String</code> representing the <code>float</code>
210 * public static String toString(float f) { return VMFloat.toString(f); }
214 * Convert a float value to a hexadecimal string. This converts as follows:
216 * <li>A NaN value is converted to the string "NaN".
217 * <li>Positive infinity is converted to the string "Infinity".
218 * <li>Negative infinity is converted to the string "-Infinity".
219 * <li>For all other values, the first character of the result is '-' if the
220 * value is negative. This is followed by '0x1.' if the value is normal, and
221 * '0x0.' if the value is denormal. This is then followed by a (lower-case)
222 * hexadecimal representation of the mantissa, with leading zeros as required
223 * for denormal values. The next character is a 'p', and this is followed by a
224 * decimal representation of the unbiased exponent.
229 * @return the hexadecimal string representation
233 * public static String toHexString(float f) { if (isNaN(f)) return "NaN"; if
234 * (isInfinite(f)) return f < 0 ? "-Infinity" : "Infinity";
236 * int bits = floatToIntBits(f); CPStringBuilder result = new
239 * if (bits < 0) result.append('-'); result.append("0x");
241 * final int mantissaBits = 23; final int exponentBits = 8; int mantMask = (1
242 * << mantissaBits) - 1; int mantissa = bits & mantMask; int expMask = (1 <<
243 * exponentBits) - 1; int exponent = (bits >>> mantissaBits) & expMask;
245 * result.append(exponent == 0 ? '0' : '1'); result.append('.'); // For Float
246 * only, we have to adjust the mantissa. mantissa <<= 1;
247 * result.append(Integer.toHexString(mantissa)); if (exponent == 0 && mantissa
248 * != 0) { // Treat denormal specially by inserting '0's to make // the length
249 * come out right. The constants here are // to account for things like the
250 * '0x'. int offset = 4 + ((bits < 0) ? 1 : 0); // The silly +3 is here to
251 * keep the code the same between // the Float and Double cases. In Float the
252 * value is // not a multiple of 4. int desiredLength = offset + (mantissaBits
253 * + 3) / 4; while (result.length() < desiredLength) result.insert(offset,
254 * '0'); } result.append('p'); if (exponent == 0 && mantissa == 0) { // Zero,
255 * so do nothing special. } else { // Apply bias. boolean denormal = exponent
256 * == 0; exponent -= (1 << (exponentBits - 1)) - 1; // Handle denormal. if
257 * (denormal) ++exponent; }
259 * result.append(Integer.toString(exponent)); return result.toString(); }
263 * Creates a new <code>Float</code> object using the <code>String</code>.
266 * the <code>String</code> to convert
267 * @return the new <code>Float</code>
268 * @throws NumberFormatException
269 * if <code>s</code> cannot be parsed as a <code>float</code>
270 * @throws NullPointerException
271 * if <code>s</code> is null
272 * @see #parseFloat(String)
274 public static Float valueOf(String s) {
275 return valueOf(parseFloat(s));
279 * Returns a <code>Float</code> object wrapping the value. In contrast to the
280 * <code>Float</code> constructor, this method may cache some values. It is
281 * used by boxing conversion.
285 * @return the <code>Float</code>
288 public static Float valueOf(float val) {
289 if ((val == 0.0)/* && (floatToRawIntBits(val) == 0) */)
294 return new Float(val);
298 * Parse the specified <code>String</code> as a <code>float</code>. The
299 * extended BNF grammar is as follows:<br>
302 * <em>DecodableString</em>:
303 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
304 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
305 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
306 * [ <code>f</code> | <code>F</code> | <code>d</code>
307 * | <code>D</code>] )
308 * <em>FloatingPoint</em>:
309 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
310 * [ <em>Exponent</em> ] )
311 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
313 * ( ( <code>e</code> | <code>E</code> )
314 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
315 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
319 * NaN and infinity are special cases, to allow parsing of the output of
320 * toString. Otherwise, the result is determined by calculating
321 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding to
322 * the nearest float. Remember that many numbers cannot be precisely
323 * represented in floating point. In case of overflow, infinity is used, and
324 * in case of underflow, signed zero is used. Unlike Integer.parseInt, this
325 * does not accept Unicode digits outside the ASCII range.
328 * If an unexpected character is found in the <code>String</code>, a
329 * <code>NumberFormatException</code> will be thrown. Leading and trailing
330 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces internal
331 * to the actual number are not allowed.
334 * To parse numbers according to another format, consider using
335 * {@link java.text.NumberFormat}.
337 * @XXX specify where/how we are not in accord with the spec.
340 * the <code>String</code> to convert
341 * @return the <code>float</code> value of <code>s</code>
342 * @throws NumberFormatException
343 * if <code>str</code> cannot be parsed as a <code>float</code>
344 * @throws NullPointerException
345 * if <code>str</code> is null
348 * @see #POSITIVE_INFINITY
349 * @see #NEGATIVE_INFINITY
352 public static float parseFloat(String str) {
353 // return VMFloat.parseFloat(str);
354 return (float) (Double.parseDouble(str));
358 * Return <code>true</code> if the <code>float</code> has the same value as
359 * <code>NaN</code>, otherwise return <code>false</code>.
362 * the <code>float</code> to compare
363 * @return whether the argument is <code>NaN</code>
365 public static boolean isNaN(float v) {
366 // This works since NaN != NaN is the only reflexive inequality
367 // comparison which returns true.
372 * Return <code>true</code> if the <code>float</code> has a value equal to
373 * either <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
374 * otherwise return <code>false</code>.
377 * the <code>float</code> to compare
378 * @return whether the argument is (-/+) infinity
380 public static boolean isInfinite(float v) {
381 return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
385 * Return <code>true</code> if the value of this <code>Float</code> is the
386 * same as <code>NaN</code>, otherwise return <code>false</code>.
388 * @return whether this <code>Float</code> is <code>NaN</code>
390 public boolean isNaN() {
395 * Return <code>true</code> if the value of this <code>Float</code> is the
396 * same as <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
397 * otherwise return <code>false</code>.
399 * @return whether this <code>Float</code> is (-/+) infinity
401 public boolean isInfinite() {
402 return isInfinite(value);
406 * Convert the <code>float</code> value of this <code>Float</code> to a
407 * <code>String</code>. This method calls <code>Float.toString(float)</code>
408 * to do its dirty work.
410 * @return the <code>String</code> representation
411 * @see #toString(float)
414 * public String toString() { return toString(value); }
418 * Return the value of this <code>Float</code> as a <code>byte</code>.
420 * @return the byte value
423 public byte byteValue() {
428 * Return the value of this <code>Float</code> as a <code>short</code>.
430 * @return the short value
433 public short shortValue() {
434 return (short) value;
438 * Return the value of this <code>Integer</code> as an <code>int</code>.
440 * @return the int value
442 public int intValue() {
447 * Return the value of this <code>Integer</code> as a <code>long</code>.
449 * @return the long value
451 public long longValue() {
456 * Return the value of this <code>Float</code>.
458 * @return the float value
460 public float floatValue() {
465 * Return the value of this <code>Float</code> as a <code>double</code>
467 * @return the double value
469 public double doubleValue() {
474 * Return a hashcode representing this Object. <code>Float</code>'s hash code
475 * is calculated by calling <code>floatToIntBits(floatValue())</code>.
477 * @return this Object's hash code
478 * @see #floatToIntBits(float)
481 * public int hashCode() { return floatToIntBits(value); }
485 * Returns <code>true</code> if <code>obj</code> is an instance of
486 * <code>Float</code> and represents the same float value. Unlike comparing
487 * two floats with <code>==</code>, this treats two instances of
488 * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
489 * <code>-0.0</code> as unequal.
492 * Note that <code>f1.equals(f2)</code> is identical to
493 * <code>floatToIntBits(f1.floatValue()) ==
494 * floatToIntBits(f2.floatValue())</code>.
497 * the object to compare
498 * @return whether the objects are semantically equal
501 * public boolean equals(Object obj) { if (obj instanceof Float) { float f =
502 * ((Float) obj).value; return (floatToRawIntBits(value) ==
503 * floatToRawIntBits(f)) || (isNaN(value) && isNaN(f)); } return false; }
507 * Convert the float to the IEEE 754 floating-point "single format" bit
508 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23 (masked
509 * by 0x7f800000) represent the exponent, and bits 22-0 (masked by 0x007fffff)
510 * are the mantissa. This function collapses all versions of NaN to
511 * 0x7fc00000. The result of this function can be used as the argument to
512 * <code>Float.intBitsToFloat(int)</code> to obtain the original
513 * <code>float</code> value.
516 * the <code>float</code> to convert
517 * @return the bits of the <code>float</code>
518 * @see #intBitsToFloat(int)
521 * public static int floatToIntBits(float value) { if (isNaN(value)) return
522 * 0x7fc00000; else return VMFloat.floatToRawIntBits(value); }
526 * Convert the float to the IEEE 754 floating-point "single format" bit
527 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23 (masked
528 * by 0x7f800000) represent the exponent, and bits 22-0 (masked by 0x007fffff)
529 * are the mantissa. This function leaves NaN alone, rather than collapsing to
530 * a canonical value. The result of this function can be used as the argument
531 * to <code>Float.intBitsToFloat(int)</code> to obtain the original
532 * <code>float</code> value.
535 * the <code>float</code> to convert
536 * @return the bits of the <code>float</code>
537 * @see #intBitsToFloat(int)
540 * public static int floatToRawIntBits(float value) { return
541 * VMFloat.floatToRawIntBits(value); }
545 * Convert the argument in IEEE 754 floating-point "single format" bit layout
546 * to the corresponding float. Bit 31 (the most significant) is the sign bit,
547 * bits 30-23 (masked by 0x7f800000) represent the exponent, and bits 22-0
548 * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone, so
549 * that you can recover the bit pattern with
550 * <code>Float.floatToRawIntBits(float)</code>.
553 * the bits to convert
554 * @return the <code>float</code> represented by the bits
555 * @see #floatToIntBits(float)
556 * @see #floatToRawIntBits(float)
559 * public static float intBitsToFloat(int bits) { return
560 * VMFloat.intBitsToFloat(bits); }
564 * Compare two Floats numerically by comparing their <code>float</code>
565 * values. The result is positive if the first is greater, negative if the
566 * second is greater, and 0 if the two are equal. However, this special cases
567 * NaN and signed zero as follows: NaN is considered greater than all other
568 * floats, including <code>POSITIVE_INFINITY</code>, and positive zero is
569 * considered greater than negative zero.
572 * the Float to compare
573 * @return the comparison
577 * public int compareTo(Float f) { return compare(value, f.value); }
581 * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in other
582 * words this compares two floats, special casing NaN and zero, without the
583 * overhead of objects.
586 * the first float to compare
588 * the second float to compare
589 * @return the comparison
593 * public static int compare(float x, float y) { // handle the easy cases: if
594 * (x < y) return -1; if (x > y) return 1;
596 * // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
597 * int ix = floatToRawIntBits(x); int iy = floatToRawIntBits(y); if (ix == iy)
600 * // handle NaNs: if (x != x) return (y != y) ? 0 : 1; else if (y != y)
603 * // handle +/- 0.0 return (ix < iy) ? -1 : 1; }