[Java] 將字串轉成浮點數型態

所謂的浮點數型態,在這裡指的是 Float 和 Double 的型態,而前面海芋曾經介紹過如何將字串轉換成整數型態,在這裡海芋將介紹如何轉成浮點數型態。

 

首先,我們先去介紹 Double類別和 Float 類別底下的兩個 method。

public static float parseFloat(String s) throws NumberFormatException
public static double parseDouble(String s) throws NumberFormatException

 

接下來,以程式碼介紹如何使用,以轉成 Float 和 Double 為例。

 

1.轉成 Float 型態

float test = 0;
 String strFloat = "123.4"
 try{
   float = Float.parseFloat(strFloat);
 }catch(NumberFormatException e){
   System.out.println("浮點數轉換錯誤");
 }

 

2.轉成 Double 型態

 double test = 0;
 String strDouble = "123.4"
 try{
   test = Double.parseDouble(strDouble);
 }catch(NumberFormatException e){
   System.out.println("浮點數轉換錯誤");
 }
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments