Imported GNU Classpath 0.90
[official-gcc.git] / libjava / classpath / java / lang / Float.java
blobdcd5b221197e3e1c8777b29bb95a97e6174ae15b
1 /* Float.java -- object wrapper for float
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 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)
10 any later version.
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
20 02110-1301 USA.
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
25 combination.
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 package java.lang;
42 /**
43 * Instances of class <code>Float</code> represent primitive
44 * <code>float</code> values.
46 * Additionally, this class provides various helper functions and variables
47 * related to floats.
49 * @author Paul Fisher
50 * @author Andrew Haley (aph@cygnus.com)
51 * @author Eric Blake (ebb9@email.byu.edu)
52 * @since 1.0
53 * @status updated to 1.4
55 public final class Float extends Number implements Comparable
57 /**
58 * Compatible with JDK 1.0+.
60 private static final long serialVersionUID = -2671257302660747028L;
62 /**
63 * The maximum positive value a <code>double</code> may represent
64 * is 3.4028235e+38f.
66 public static final float MAX_VALUE = 3.4028235e+38f;
68 /**
69 * The minimum positive value a <code>float</code> may represent
70 * is 1.4e-45.
72 public static final float MIN_VALUE = 1.4e-45f;
74 /**
75 * The value of a float representation -1.0/0.0, negative infinity.
77 public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
79 /**
80 * The value of a float representation 1.0/0.0, positive infinity.
82 public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
84 /**
85 * All IEEE 754 values of NaN have the same value in Java.
87 public static final float NaN = 0.0f / 0.0f;
89 /**
90 * The primitive type <code>float</code> is represented by this
91 * <code>Class</code> object.
92 * @since 1.1
94 public static final Class TYPE = VMClassLoader.getPrimitiveClass('F');
96 /**
97 * The number of bits needed to represent a <code>float</code>.
98 * @since 1.5
100 public static final int SIZE = 32;
103 * The immutable value of this Float.
105 * @serial the wrapped float
107 private final float value;
110 * Create a <code>Float</code> from the primitive <code>float</code>
111 * specified.
113 * @param value the <code>float</code> argument
115 public Float(float value)
117 this.value = value;
121 * Create a <code>Float</code> from the primitive <code>double</code>
122 * specified.
124 * @param value the <code>double</code> argument
126 public Float(double value)
128 this.value = (float) value;
132 * Create a <code>Float</code> from the specified <code>String</code>.
133 * This method calls <code>Float.parseFloat()</code>.
135 * @param s the <code>String</code> to convert
136 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
137 * <code>float</code>
138 * @throws NullPointerException if <code>s</code> is null
139 * @see #parseFloat(String)
141 public Float(String s)
143 value = parseFloat(s);
147 * Convert the <code>float</code> to a <code>String</code>.
148 * Floating-point string representation is fairly complex: here is a
149 * rundown of the possible values. "<code>[-]</code>" indicates that a
150 * negative sign will be printed if the value (or exponent) is negative.
151 * "<code>&lt;number&gt;</code>" means a string of digits ('0' to '9').
152 * "<code>&lt;digit&gt;</code>" means a single digit ('0' to '9').<br>
154 * <table border=1>
155 * <tr><th>Value of Float</th><th>String Representation</th></tr>
156 * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
157 * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
158 * <td><code>[-]number.number</code></td></tr>
159 * <tr><td>Other numeric value</td>
160 * <td><code>[-]&lt;digit&gt;.&lt;number&gt;
161 * E[-]&lt;number&gt;</code></td></tr>
162 * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
163 * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
164 * </table>
166 * Yes, negative zero <em>is</em> a possible value. Note that there is
167 * <em>always</em> a <code>.</code> and at least one digit printed after
168 * it: even if the number is 3, it will be printed as <code>3.0</code>.
169 * After the ".", all digits will be printed except trailing zeros. The
170 * result is rounded to the shortest decimal number which will parse back
171 * to the same float.
173 * <p>To create other output formats, use {@link java.text.NumberFormat}.
175 * @XXX specify where we are not in accord with the spec.
177 * @param f the <code>float</code> to convert
178 * @return the <code>String</code> representing the <code>float</code>
180 public static String toString(float f)
182 return VMDouble.toString(f, true);
186 * Convert a float value to a hexadecimal string. This converts as
187 * follows:
188 * <ul>
189 * <li> A NaN value is converted to the string "NaN".
190 * <li> Positive infinity is converted to the string "Infinity".
191 * <li> Negative infinity is converted to the string "-Infinity".
192 * <li> For all other values, the first character of the result is '-'
193 * if the value is negative. This is followed by '0x1.' if the
194 * value is normal, and '0x0.' if the value is denormal. This is
195 * then followed by a (lower-case) hexadecimal representation of the
196 * mantissa, with leading zeros as required for denormal values.
197 * The next character is a 'p', and this is followed by a decimal
198 * representation of the unbiased exponent.
199 * </ul>
200 * @param f the float value
201 * @return the hexadecimal string representation
202 * @since 1.5
204 public static String toHexString(float f)
206 if (isNaN(f))
207 return "NaN";
208 if (isInfinite(f))
209 return f < 0 ? "-Infinity" : "Infinity";
211 int bits = floatToIntBits(f);
212 StringBuilder result = new StringBuilder();
214 if (bits < 0)
215 result.append('-');
216 result.append("0x");
218 final int mantissaBits = 23;
219 final int exponentBits = 8;
220 int mantMask = (1 << mantissaBits) - 1;
221 int mantissa = bits & mantMask;
222 int expMask = (1 << exponentBits) - 1;
223 int exponent = (bits >>> mantissaBits) & expMask;
225 result.append(exponent == 0 ? '0' : '1');
226 result.append('.');
227 // For Float only, we have to adjust the mantissa.
228 mantissa <<= 1;
229 result.append(Integer.toHexString(mantissa));
230 if (exponent == 0 && mantissa != 0)
232 // Treat denormal specially by inserting '0's to make
233 // the length come out right. The constants here are
234 // to account for things like the '0x'.
235 int offset = 4 + ((bits < 0) ? 1 : 0);
236 // The silly +3 is here to keep the code the same between
237 // the Float and Double cases. In Float the value is
238 // not a multiple of 4.
239 int desiredLength = offset + (mantissaBits + 3) / 4;
240 while (result.length() < desiredLength)
241 result.insert(offset, '0');
243 result.append('p');
244 if (exponent == 0 && mantissa == 0)
246 // Zero, so do nothing special.
248 else
250 // Apply bias.
251 boolean denormal = exponent == 0;
252 exponent -= (1 << (exponentBits - 1)) - 1;
253 // Handle denormal.
254 if (denormal)
255 ++exponent;
258 result.append(Integer.toString(exponent));
259 return result.toString();
263 * Creates a new <code>Float</code> object using the <code>String</code>.
265 * @param s the <code>String</code> to convert
266 * @return the new <code>Float</code>
267 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
268 * <code>float</code>
269 * @throws NullPointerException if <code>s</code> is null
270 * @see #parseFloat(String)
272 public static Float valueOf(String s)
274 return new Float(parseFloat(s));
278 * Returns a <code>Float</code> object wrapping the value.
279 * In contrast to the <code>Float</code> constructor, this method
280 * may cache some values. It is used by boxing conversion.
282 * @param val the value to wrap
283 * @return the <code>Float</code>
285 * @since 1.5
287 public static Float valueOf(float val)
289 // We don't actually cache, but we could.
290 return new Float(val);
294 * Parse the specified <code>String</code> as a <code>float</code>. The
295 * extended BNF grammar is as follows:<br>
296 * <pre>
297 * <em>DecodableString</em>:
298 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
299 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
300 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
301 * [ <code>f</code> | <code>F</code> | <code>d</code>
302 * | <code>D</code>] )
303 * <em>FloatingPoint</em>:
304 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
305 * [ <em>Exponent</em> ] )
306 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
307 * <em>Exponent</em>:
308 * ( ( <code>e</code> | <code>E</code> )
309 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
310 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
311 * </pre>
313 * <p>NaN and infinity are special cases, to allow parsing of the output
314 * of toString. Otherwise, the result is determined by calculating
315 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
316 * to the nearest float. Remember that many numbers cannot be precisely
317 * represented in floating point. In case of overflow, infinity is used,
318 * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
319 * this does not accept Unicode digits outside the ASCII range.
321 * <p>If an unexpected character is found in the <code>String</code>, a
322 * <code>NumberFormatException</code> will be thrown. Leading and trailing
323 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
324 * internal to the actual number are not allowed.
326 * <p>To parse numbers according to another format, consider using
327 * {@link java.text.NumberFormat}.
329 * @XXX specify where/how we are not in accord with the spec.
331 * @param str the <code>String</code> to convert
332 * @return the <code>float</code> value of <code>s</code>
333 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
334 * <code>float</code>
335 * @throws NullPointerException if <code>s</code> is null
336 * @see #MIN_VALUE
337 * @see #MAX_VALUE
338 * @see #POSITIVE_INFINITY
339 * @see #NEGATIVE_INFINITY
340 * @since 1.2
342 public static float parseFloat(String str)
344 // XXX Rounding parseDouble() causes some errors greater than 1 ulp from
345 // the infinitely precise decimal.
346 return (float) Double.parseDouble(str);
350 * Return <code>true</code> if the <code>float</code> has the same
351 * value as <code>NaN</code>, otherwise return <code>false</code>.
353 * @param v the <code>float</code> to compare
354 * @return whether the argument is <code>NaN</code>
356 public static boolean isNaN(float v)
358 // This works since NaN != NaN is the only reflexive inequality
359 // comparison which returns true.
360 return v != v;
364 * Return <code>true</code> if the <code>float</code> has a value
365 * equal to either <code>NEGATIVE_INFINITY</code> or
366 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
368 * @param v the <code>float</code> to compare
369 * @return whether the argument is (-/+) infinity
371 public static boolean isInfinite(float v)
373 return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
377 * Return <code>true</code> if the value of this <code>Float</code>
378 * is the same as <code>NaN</code>, otherwise return <code>false</code>.
380 * @return whether this <code>Float</code> is <code>NaN</code>
382 public boolean isNaN()
384 return isNaN(value);
388 * Return <code>true</code> if the value of this <code>Float</code>
389 * is the same as <code>NEGATIVE_INFINITY</code> or
390 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
392 * @return whether this <code>Float</code> is (-/+) infinity
394 public boolean isInfinite()
396 return isInfinite(value);
400 * Convert the <code>float</code> value of this <code>Float</code>
401 * to a <code>String</code>. This method calls
402 * <code>Float.toString(float)</code> to do its dirty work.
404 * @return the <code>String</code> representation
405 * @see #toString(float)
407 public String toString()
409 return toString(value);
413 * Return the value of this <code>Float</code> as a <code>byte</code>.
415 * @return the byte value
416 * @since 1.1
418 public byte byteValue()
420 return (byte) value;
424 * Return the value of this <code>Float</code> as a <code>short</code>.
426 * @return the short value
427 * @since 1.1
429 public short shortValue()
431 return (short) value;
435 * Return the value of this <code>Integer</code> as an <code>int</code>.
437 * @return the int value
439 public int intValue()
441 return (int) value;
445 * Return the value of this <code>Integer</code> as a <code>long</code>.
447 * @return the long value
449 public long longValue()
451 return (long) value;
455 * Return the value of this <code>Float</code>.
457 * @return the float value
459 public float floatValue()
461 return value;
465 * Return the value of this <code>Float</code> as a <code>double</code>
467 * @return the double value
469 public double doubleValue()
471 return value;
475 * Return a hashcode representing this Object. <code>Float</code>'s hash
476 * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
478 * @return this Object's hash code
479 * @see #floatToIntBits(float)
481 public int hashCode()
483 return floatToIntBits(value);
487 * Returns <code>true</code> if <code>obj</code> is an instance of
488 * <code>Float</code> and represents the same float value. Unlike comparing
489 * two floats with <code>==</code>, this treats two instances of
490 * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
491 * <code>-0.0</code> as unequal.
493 * <p>Note that <code>f1.equals(f2)</code> is identical to
494 * <code>floatToIntBits(f1.floatValue()) ==
495 * floatToIntBits(f2.floatValue())</code>.
497 * @param obj the object to compare
498 * @return whether the objects are semantically equal
500 public boolean equals(Object obj)
502 if (! (obj instanceof Float))
503 return false;
505 float f = ((Float) obj).value;
507 // Avoid call to native method. However, some implementations, like gcj,
508 // are better off using floatToIntBits(value) == floatToIntBits(f).
509 // Check common case first, then check NaN and 0.
510 if (value == f)
511 return (value != 0) || (1 / value == 1 / f);
512 return isNaN(value) && isNaN(f);
516 * Convert the float to the IEEE 754 floating-point "single format" bit
517 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
518 * (masked by 0x7f800000) represent the exponent, and bits 22-0
519 * (masked by 0x007fffff) are the mantissa. This function collapses all
520 * versions of NaN to 0x7fc00000. The result of this function can be used
521 * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
522 * original <code>float</code> value.
524 * @param value the <code>float</code> to convert
525 * @return the bits of the <code>float</code>
526 * @see #intBitsToFloat(int)
528 public static int floatToIntBits(float value)
530 return VMFloat.floatToIntBits(value);
534 * Convert the float to the IEEE 754 floating-point "single format" bit
535 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
536 * (masked by 0x7f800000) represent the exponent, and bits 22-0
537 * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
538 * rather than collapsing to a canonical value. The result of this function
539 * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
540 * obtain the original <code>float</code> value.
542 * @param value the <code>float</code> to convert
543 * @return the bits of the <code>float</code>
544 * @see #intBitsToFloat(int)
546 public static int floatToRawIntBits(float value)
548 return VMFloat.floatToRawIntBits(value);
552 * Convert the argument in IEEE 754 floating-point "single format" bit
553 * layout to the corresponding float. Bit 31 (the most significant) is the
554 * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
555 * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
556 * NaN alone, so that you can recover the bit pattern with
557 * <code>Float.floatToRawIntBits(float)</code>.
559 * @param bits the bits to convert
560 * @return the <code>float</code> represented by the bits
561 * @see #floatToIntBits(float)
562 * @see #floatToRawIntBits(float)
564 public static float intBitsToFloat(int bits)
566 return VMFloat.intBitsToFloat(bits);
570 * Compare two Floats numerically by comparing their <code>float</code>
571 * values. The result is positive if the first is greater, negative if the
572 * second is greater, and 0 if the two are equal. However, this special
573 * cases NaN and signed zero as follows: NaN is considered greater than
574 * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
575 * zero is considered greater than negative zero.
577 * @param f the Float to compare
578 * @return the comparison
579 * @since 1.2
581 public int compareTo(Float f)
583 return compare(value, f.value);
587 * Behaves like <code>compareTo(Float)</code> unless the Object
588 * is not an <code>Float</code>.
590 * @param o the object to compare
591 * @return the comparison
592 * @throws ClassCastException if the argument is not a <code>Float</code>
593 * @see #compareTo(Float)
594 * @see Comparable
595 * @since 1.2
597 public int compareTo(Object o)
599 return compare(value, ((Float) o).value);
603 * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
604 * other words this compares two floats, special casing NaN and zero,
605 * without the overhead of objects.
607 * @param x the first float to compare
608 * @param y the second float to compare
609 * @return the comparison
610 * @since 1.4
612 public static int compare(float x, float y)
614 if (isNaN(x))
615 return isNaN(y) ? 0 : 1;
616 if (isNaN(y))
617 return -1;
618 // recall that 0.0 == -0.0, so we convert to infinities and try again
619 if (x == 0 && y == 0)
620 return (int) (1 / x - 1 / y);
621 if (x == y)
622 return 0;
624 return x > y ? 1 : -1;