Java - Number floatValue() 方法



Java 的 Number floatValue() 方法用於將指定數字的值轉換為浮點值。

float 是一種原始資料型別,是單精度 32 位 IEEE 754 浮點值。float 值的範圍從 3.40282347 x 1038 到 1.40239846 x 10-45。當需要在儲存大量浮點陣列時節省記憶體時,使用此資料型別。

float 的預設值為 0.0f;其預設大小為 4 個位元組。

注意 - 此轉換可能涉及給定數字的舍入或截斷。

語法

以下是 Java Number floatValue() 方法的語法

public abstract float floatValue()

引數

此方法不接受任何引數。

返回值

此方法在轉換給定數值後返回浮點值。

從 Integer 獲取浮點值示例

以下示例演示了 Java Number floatValue() 方法的用法。整數值被賦給 Integer 類引用變數;並呼叫在此建立的物件上呼叫此方法以將整數值轉換為浮點值。

package com.tutorialspoint;

public class NumberFloatVal {
   public static void main(String[] args) {

      // get a number as integer
      Integer x = 123456;

      // print their value as float
      System.out.println("x as integer: " + x + ", x as float: " + x.floatValue());
   }
}

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

x as integer: 123456, x as float: 123456.0

從 Long 獲取浮點值示例

在此示例中,我們首先將長整數值賦給 Long 類引用變數。然後在此建立的 Float 物件上呼叫此方法,並將長整數值轉換為浮點值。

package com.tutorialspoint;

public class NumberFloatVal {
   public static void main(String[] args) {

      // Get a number as long
      Long x = (long) 192873;
 
      // Print their value as float
      System.out.println("x as long: " + x + ", x as float: " + x.floatValue());
   }  
}

編譯並執行程式後,輸出顯示為:

x as long: 192873, x as float: 192873.0

從 Double 獲取浮點值示例

在這裡,與前面的示例類似,Double 類引用變數被賦予一個雙精度值。然後在此物件上呼叫此方法以將其雙精度值轉換為相應的浮點值。

package com.tutorialspoint;

public class NumberFloatVal {
   public static void main(String[] args) {

      // get a number as double
      Double x = 92873d;
  
      // print their value as float
      System.out.println("x as double: " + x + ", x as float: " + x.floatValue());
   }  
}

上述程式的輸出如下所示:

x as double: 92873.0, x as float: 92873.0

從 Byte 獲取浮點值示例

我們還可以將位元組值轉換為其對應的雙精度值。在建立物件之後,將位元組值賦給 Byte 類引用變數。此方法將在此物件上呼叫,以將位元組值轉換為雙精度值。

package com.tutorialspoint;

public class NumberFloatVal {
   public static void main(String[] args) {

      // get a number as byte
      Byte x = -120;
  
      // print their value as float
      System.out.println("x as byte: " + x + ", x as float: " + x.floatValue());
   }  
}

程式編譯並執行後,輸出顯示如下:

x as byte: -120, x as float: -120.0
java_lang_number.htm
廣告
© . All rights reserved.