libjava/ChangeLog:
[official-gcc.git] / libjava / classpath / java / lang / Float.java
blob63e43c257ea997335aac03888b45df0410b070d4
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)
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 import gnu.java.lang.CPStringBuilder;
44 /**
45 * Instances of class <code>Float</code> represent primitive
46 * <code>float</code> values.
48 * Additionally, this class provides various helper functions and variables
49 * related to floats.
51 * @author Paul Fisher
52 * @author Andrew Haley (aph@cygnus.com)
53 * @author Eric Blake (ebb9@email.byu.edu)
54 * @author Tom Tromey (tromey@redhat.com)
55 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
56 * @since 1.0
57 * @status partly updated to 1.5
59 public final class Float extends Number implements Comparable<Float>
61 /**
62 * Compatible with JDK 1.0+.
64 private static final long serialVersionUID = -2671257302660747028L;
66 /**
67 * The maximum positive value a <code>double</code> may represent
68 * is 3.4028235e+38f.
70 public static final float MAX_VALUE = 3.4028235e+38f;
72 /**
73 * The minimum positive value a <code>float</code> may represent
74 * is 1.4e-45.
76 public static final float MIN_VALUE = 1.4e-45f;
78 /**
79 * The value of a float representation -1.0/0.0, negative infinity.
81 public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
83 /**
84 * The value of a float representation 1.0/0.0, positive infinity.
86 public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
88 /**
89 * All IEEE 754 values of NaN have the same value in Java.
91 public static final float NaN = 0.0f / 0.0f;
93 /**
94 * The primitive type <code>float</code> is represented by this
95 * <code>Class</code> object.
96 * @since 1.1
98 public static final Class<Float> TYPE = (Class<Float>) VMClassLoader.getPrimitiveClass('F');
101 * The number of bits needed to represent a <code>float</code>.
102 * @since 1.5
104 public static final int SIZE = 32;
107 * Cache representation of 0
109 private static final Float ZERO = new Float(0.0f);
112 * Cache representation of 1
114 private static final Float ONE = new Float(1.0f);
117 * The immutable value of this Float.
119 * @serial the wrapped float
121 private final float value;
124 * Create a <code>Float</code> from the primitive <code>float</code>
125 * specified.
127 * @param value the <code>float</code> argument
129 public Float(float value)
131 this.value = value;
135 * Create a <code>Float</code> from the primitive <code>double</code>
136 * specified.
138 * @param value the <code>double</code> argument
140 public Float(double value)
142 this.value = (float) value;
146 * Create a <code>Float</code> from the specified <code>String</code>.
147 * This method calls <code>Float.parseFloat()</code>.
149 * @param s the <code>String</code> to convert
150 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
151 * <code>float</code>
152 * @throws NullPointerException if <code>s</code> is null
153 * @see #parseFloat(String)
155 public Float(String s)
157 value = parseFloat(s);
161 * Convert the <code>float</code> to a <code>String</code>.
162 * Floating-point string representation is fairly complex: here is a
163 * rundown of the possible values. "<code>[-]</code>" indicates that a
164 * negative sign will be printed if the value (or exponent) is negative.
165 * "<code>&lt;number&gt;</code>" means a string of digits ('0' to '9').
166 * "<code>&lt;digit&gt;</code>" means a single digit ('0' to '9').<br>
168 * <table border=1>
169 * <tr><th>Value of Float</th><th>String Representation</th></tr>
170 * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
171 * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
172 * <td><code>[-]number.number</code></td></tr>
173 * <tr><td>Other numeric value</td>
174 * <td><code>[-]&lt;digit&gt;.&lt;number&gt;
175 * E[-]&lt;number&gt;</code></td></tr>
176 * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
177 * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
178 * </table>
180 * Yes, negative zero <em>is</em> a possible value. Note that there is
181 * <em>always</em> a <code>.</code> and at least one digit printed after
182 * it: even if the number is 3, it will be printed as <code>3.0</code>.
183 * After the ".", all digits will be printed except trailing zeros. The
184 * result is rounded to the shortest decimal number which will parse back
185 * to the same float.
187 * <p>To create other output formats, use {@link java.text.NumberFormat}.
189 * @XXX specify where we are not in accord with the spec.
191 * @param f the <code>float</code> to convert
192 * @return the <code>String</code> representing the <code>float</code>
194 public static String toString(float f)
196 return VMFloat.toString(f);
200 * Convert a float value to a hexadecimal string. This converts as
201 * follows:
202 * <ul>
203 * <li> A NaN value is converted to the string "NaN".
204 * <li> Positive infinity is converted to the string "Infinity".
205 * <li> Negative infinity is converted to the string "-Infinity".
206 * <li> For all other values, the first character of the result is '-'
207 * if the value is negative. This is followed by '0x1.' if the
208 * value is normal, and '0x0.' if the value is denormal. This is
209 * then followed by a (lower-case) hexadecimal representation of the
210 * mantissa, with leading zeros as required for denormal values.
211 * The next character is a 'p', and this is followed by a decimal
212 * representation of the unbiased exponent.
213 * </ul>
214 * @param f the float value
215 * @return the hexadecimal string representation
216 * @since 1.5
218 public static String toHexString(float f)
220 if (isNaN(f))
221 return "NaN";
222 if (isInfinite(f))
223 return f < 0 ? "-Infinity" : "Infinity";
225 int bits = floatToIntBits(f);
226 CPStringBuilder result = new CPStringBuilder();
228 if (bits < 0)
229 result.append('-');
230 result.append("0x");
232 final int mantissaBits = 23;
233 final int exponentBits = 8;
234 int mantMask = (1 << mantissaBits) - 1;
235 int mantissa = bits & mantMask;
236 int expMask = (1 << exponentBits) - 1;
237 int exponent = (bits >>> mantissaBits) & expMask;
239 result.append(exponent == 0 ? '0' : '1');
240 result.append('.');
241 // For Float only, we have to adjust the mantissa.
242 mantissa <<= 1;
243 result.append(Integer.toHexString(mantissa));
244 if (exponent == 0 && mantissa != 0)
246 // Treat denormal specially by inserting '0's to make
247 // the length come out right. The constants here are
248 // to account for things like the '0x'.
249 int offset = 4 + ((bits < 0) ? 1 : 0);
250 // The silly +3 is here to keep the code the same between
251 // the Float and Double cases. In Float the value is
252 // not a multiple of 4.
253 int desiredLength = offset + (mantissaBits + 3) / 4;
254 while (result.length() < desiredLength)
255 result.insert(offset, '0');
257 result.append('p');
258 if (exponent == 0 && mantissa == 0)
260 // Zero, so do nothing special.
262 else
264 // Apply bias.
265 boolean denormal = exponent == 0;
266 exponent -= (1 << (exponentBits - 1)) - 1;
267 // Handle denormal.
268 if (denormal)
269 ++exponent;
272 result.append(Integer.toString(exponent));
273 return result.toString();
277 * Creates a new <code>Float</code> object using the <code>String</code>.
279 * @param s the <code>String</code> to convert
280 * @return the new <code>Float</code>
281 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
282 * <code>float</code>
283 * @throws NullPointerException if <code>s</code> is null
284 * @see #parseFloat(String)
286 public static Float valueOf(String s)
288 return valueOf(parseFloat(s));
292 * Returns a <code>Float</code> object wrapping the value.
293 * In contrast to the <code>Float</code> constructor, this method
294 * may cache some values. It is used by boxing conversion.
296 * @param val the value to wrap
297 * @return the <code>Float</code>
298 * @since 1.5
300 public static Float valueOf(float val)
302 if ((val == 0.0) && (floatToRawIntBits(val) == 0))
303 return ZERO;
304 else if (val == 1.0)
305 return ONE;
306 else
307 return new Float(val);
311 * Parse the specified <code>String</code> as a <code>float</code>. The
312 * extended BNF grammar is as follows:<br>
313 * <pre>
314 * <em>DecodableString</em>:
315 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
316 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
317 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
318 * [ <code>f</code> | <code>F</code> | <code>d</code>
319 * | <code>D</code>] )
320 * <em>FloatingPoint</em>:
321 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
322 * [ <em>Exponent</em> ] )
323 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
324 * <em>Exponent</em>:
325 * ( ( <code>e</code> | <code>E</code> )
326 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
327 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
328 * </pre>
330 * <p>NaN and infinity are special cases, to allow parsing of the output
331 * of toString. Otherwise, the result is determined by calculating
332 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
333 * to the nearest float. Remember that many numbers cannot be precisely
334 * represented in floating point. In case of overflow, infinity is used,
335 * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
336 * this does not accept Unicode digits outside the ASCII range.
338 * <p>If an unexpected character is found in the <code>String</code>, a
339 * <code>NumberFormatException</code> will be thrown. Leading and trailing
340 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
341 * internal to the actual number are not allowed.
343 * <p>To parse numbers according to another format, consider using
344 * {@link java.text.NumberFormat}.
346 * @XXX specify where/how we are not in accord with the spec.
348 * @param str the <code>String</code> to convert
349 * @return the <code>float</code> value of <code>s</code>
350 * @throws NumberFormatException if <code>str</code> cannot be parsed as a
351 * <code>float</code>
352 * @throws NullPointerException if <code>str</code> is null
353 * @see #MIN_VALUE
354 * @see #MAX_VALUE
355 * @see #POSITIVE_INFINITY
356 * @see #NEGATIVE_INFINITY
357 * @since 1.2
359 public static float parseFloat(String str)
361 return VMFloat.parseFloat(str);
365 * Return <code>true</code> if the <code>float</code> has the same
366 * value as <code>NaN</code>, otherwise return <code>false</code>.
368 * @param v the <code>float</code> to compare
369 * @return whether the argument is <code>NaN</code>
371 public static boolean isNaN(float v)
373 // This works since NaN != NaN is the only reflexive inequality
374 // comparison which returns true.
375 return v != v;
379 * Return <code>true</code> if the <code>float</code> has a value
380 * equal to either <code>NEGATIVE_INFINITY</code> or
381 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
383 * @param v the <code>float</code> to compare
384 * @return whether the argument is (-/+) infinity
386 public static boolean isInfinite(float v)
388 return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
392 * Return <code>true</code> if the value of this <code>Float</code>
393 * is the same as <code>NaN</code>, otherwise return <code>false</code>.
395 * @return whether this <code>Float</code> is <code>NaN</code>
397 public boolean isNaN()
399 return isNaN(value);
403 * Return <code>true</code> if the value of this <code>Float</code>
404 * is the same as <code>NEGATIVE_INFINITY</code> or
405 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
407 * @return whether this <code>Float</code> is (-/+) infinity
409 public boolean isInfinite()
411 return isInfinite(value);
415 * Convert the <code>float</code> value of this <code>Float</code>
416 * to a <code>String</code>. This method calls
417 * <code>Float.toString(float)</code> to do its dirty work.
419 * @return the <code>String</code> representation
420 * @see #toString(float)
422 public String toString()
424 return toString(value);
428 * Return the value of this <code>Float</code> as a <code>byte</code>.
430 * @return the byte value
431 * @since 1.1
433 public byte byteValue()
435 return (byte) value;
439 * Return the value of this <code>Float</code> as a <code>short</code>.
441 * @return the short value
442 * @since 1.1
444 public short shortValue()
446 return (short) value;
450 * Return the value of this <code>Integer</code> as an <code>int</code>.
452 * @return the int value
454 public int intValue()
456 return (int) value;
460 * Return the value of this <code>Integer</code> as a <code>long</code>.
462 * @return the long value
464 public long longValue()
466 return (long) value;
470 * Return the value of this <code>Float</code>.
472 * @return the float value
474 public float floatValue()
476 return value;
480 * Return the value of this <code>Float</code> as a <code>double</code>
482 * @return the double value
484 public double doubleValue()
486 return value;
490 * Return a hashcode representing this Object. <code>Float</code>'s hash
491 * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
493 * @return this Object's hash code
494 * @see #floatToIntBits(float)
496 public int hashCode()
498 return floatToIntBits(value);
502 * Returns <code>true</code> if <code>obj</code> is an instance of
503 * <code>Float</code> and represents the same float value. Unlike comparing
504 * two floats with <code>==</code>, this treats two instances of
505 * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
506 * <code>-0.0</code> as unequal.
508 * <p>Note that <code>f1.equals(f2)</code> is identical to
509 * <code>floatToIntBits(f1.floatValue()) ==
510 * floatToIntBits(f2.floatValue())</code>.
512 * @param obj the object to compare
513 * @return whether the objects are semantically equal
515 public boolean equals(Object obj)
517 if (obj instanceof Float)
519 float f = ((Float) obj).value;
520 return (floatToRawIntBits(value) == floatToRawIntBits(f)) ||
521 (isNaN(value) && isNaN(f));
523 return false;
527 * Convert the float to the IEEE 754 floating-point "single format" bit
528 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
529 * (masked by 0x7f800000) represent the exponent, and bits 22-0
530 * (masked by 0x007fffff) are the mantissa. This function collapses all
531 * versions of NaN to 0x7fc00000. The result of this function can be used
532 * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
533 * original <code>float</code> value.
535 * @param value the <code>float</code> to convert
536 * @return the bits of the <code>float</code>
537 * @see #intBitsToFloat(int)
539 public static int floatToIntBits(float value)
541 if (isNaN(value))
542 return 0x7fc00000;
543 else
544 return VMFloat.floatToRawIntBits(value);
548 * Convert the float to the IEEE 754 floating-point "single format" bit
549 * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
550 * (masked by 0x7f800000) represent the exponent, and bits 22-0
551 * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
552 * rather than collapsing to a canonical value. The result of this function
553 * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
554 * obtain the original <code>float</code> value.
556 * @param value the <code>float</code> to convert
557 * @return the bits of the <code>float</code>
558 * @see #intBitsToFloat(int)
560 public static int floatToRawIntBits(float value)
562 return VMFloat.floatToRawIntBits(value);
566 * Convert the argument in IEEE 754 floating-point "single format" bit
567 * layout to the corresponding float. Bit 31 (the most significant) is the
568 * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
569 * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
570 * NaN alone, so that you can recover the bit pattern with
571 * <code>Float.floatToRawIntBits(float)</code>.
573 * @param bits the bits to convert
574 * @return the <code>float</code> represented by the bits
575 * @see #floatToIntBits(float)
576 * @see #floatToRawIntBits(float)
578 public static float intBitsToFloat(int bits)
580 return VMFloat.intBitsToFloat(bits);
584 * Compare two Floats numerically by comparing their <code>float</code>
585 * values. The result is positive if the first is greater, negative if the
586 * second is greater, and 0 if the two are equal. However, this special
587 * cases NaN and signed zero as follows: NaN is considered greater than
588 * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
589 * zero is considered greater than negative zero.
591 * @param f the Float to compare
592 * @return the comparison
593 * @since 1.2
595 public int compareTo(Float f)
597 return compare(value, f.value);
601 * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
602 * other words this compares two floats, special casing NaN and zero,
603 * without the overhead of objects.
605 * @param x the first float to compare
606 * @param y the second float to compare
607 * @return the comparison
608 * @since 1.4
610 public static int compare(float x, float y)
612 // handle the easy cases:
613 if (x < y)
614 return -1;
615 if (x > y)
616 return 1;
618 // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
619 int ix = floatToRawIntBits(x);
620 int iy = floatToRawIntBits(y);
621 if (ix == iy)
622 return 0;
624 // handle NaNs:
625 if (x != x)
626 return (y != y) ? 0 : 1;
627 else if (y != y)
628 return -1;
630 // handle +/- 0.0
631 return (ix < iy) ? -1 : 1;