Java 简明教程

Java - Float class with Examples

Introduction

Java Float 类将原生类型 float 的值包装在一个对象中。类型为 Float 的对象包含一个单一字段,其类型为 float。

The Java Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.

Class Declaration

以下是 java.lang.Float 类的声明:

Following is the declaration for java.lang.Float class −

public final class Float
   extends Number
      implements Comparable<Float>

Field

以下是 java.lang.Float 类的字段:

Following are the fields for java.lang.Float class −

  1. static int MAX_EXPONENT − This is Maximum exponent a finite float variable may have.

  2. static float MAX_VALUE − This is a constant holding the largest positive finite value of type float, (2-2-23)·2127.

  3. static int MIN_EXPONENT − This is minimum exponent a normalized float variable may have.

  4. static float MIN_NORMAL − This is a constant holding the smallest positive normal value of type float, 2-126.

  5. static float MIN_VALUE − This is a constant holding the smallest positive nonzero value of type float, 2-149.

  6. static float NaN − This is a constant holding a Not-a-Number (NaN) value of type float.

  7. static float NEGATIVE_INFINITY − This is a constant holding the negative infinity of type float.

  8. static float POSITIVE_INFINITY − This is a constant holding the positive infinity of type float.

  9. static int SIZE − This is the number of bits used to represent a float value.

  10. static Class<Float> TYPE − This is the Class instance representing the primitive type float.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.lang.Object

Example

以下示例演示了使用 Float 类从字符串获取浮点数。

The following example shows the usage of Float class to get float from a string.

package com.tutorialspoint;

public class FloatDemo {

   public static void main(String[] args) {

      // create a String s and assign value to it
      String s = "+120";

      // create a Float object f
      Float f;

      // get the value of float from string
      f = Float.valueOf(s);

      // print the value
      System.out.println( "Float value of string " + s + " is " + f );
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Float value of string +120 is 120.0