Java - Short floatValue() 方法



**Java Short floatValue() 方法** 在進行擴充套件原始型別轉換(將較小的資料型別轉換為較大的資料型別)後,檢索給定 short 值的等效 float 值。float 資料型別可以儲存範圍在 3.4e-038 到 3.4e+038 之間的分數。

這可能涉及舍入或截斷。在 Java 程式設計中,截斷是指從字串右側刪除某些 float 或 double 型別數字。舍入是指將給定值四捨五入到其最接近的 float 值。

語法

以下是 **Java Short floatValue()** 方法的語法:

public float floatValue()

引數

此方法不接受任何引數。

返回值

此方法在轉換為 float 型別後,返回此物件表示的數值。

從具有正值的 Short 獲取 float 值示例

以下示例演示了透過建立 Short 物件 'obj' 併為其賦值來使用 Java Short floatValue() 方法。此後,透過在 Short 物件上呼叫該方法來返回 short 的等效 float 值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // returns the float value of this Short object
      Short obj = new Short("5");
      float f = obj.floatValue();
      System.out.println("Value = " + f);
      obj = new Short("32");
      f = obj.floatValue();
      System.out.println("Value = " + f);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value = 5.0
Value = 32.0

從具有負值的 Short 獲取 float 值示例

以下是 Java Short floatValue() 方法的一個示例。在這裡,我們將負 short 值分配給建立的 Short 物件“obj”,並列印其等效的 float 值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      Short obj = new Short("-65");
      float f = obj.floatValue();
      System.out.println("Value = " + f);
   }
} 

輸出

以下是上述程式碼的輸出:

Value = -65.0

從具有正值的 Short 獲取 float 值示例

在以下示例中,建立了一個值為“8986”的 Short 物件,並使用 Java Short floatValue() 方法將其轉換為 float:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      short obj = 8986;
      Short s = new Short(obj);
      System.out.println("The Short value is = " + s);
      
      // Short into float conversion
      float f = s.floatValue();
      System.out.println("The converted Float value is = " + f);
   }
}

輸出

在執行上述程式時,將獲得如下輸出:

The Short value is = 8986
The converted Float value is = 8986.0

從具有正值的 Short 獲取 float 值示例

以下是 floatValue() 方法的另一個示例:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      
      // initializing the variables
      short value1 = 76;
      short value2 = 87;
      
      // Returning the short value represented by this Short object 'res1'
      // and converting it to a float by calling res1.floatValue()
      Short res1 = new Short(value1);
      
      // Printing the res1 result
      System.out.println("The float value of res1 is: " + res1.floatValue());
      
      // Returning the short value represented by this Short object 'res1'
      // and converting it to a float by calling res2.floatValue()
      Short res2 = new Short(value2);
      
      // Printing the res2 result
      System.out.println("The float value of res2 is: " + res2.floatValue());
   }
}

輸出

在執行上述程式碼時,我們得到以下輸出:

The float value of res1 is: 76.0
The float value of res2 is: 87.0
java_lang_short.htm
廣告

© . All rights reserved.