2017-01-09 63 views
-2
String number="3"; 

使用:轉換字符串到浮點數數的Android

Float f=Float.parseFloat(number);` 

是給錯誤。

如何將其轉換爲float

代碼:

`JSONObject jsonObject=new JSONObject(s); 
      JSONArray jsonArray=jsonObject.getJSONArray("response2"); 
      for(int i=0;i<jsonArray.length();i++) 

       jsonObject=jsonArray.optJSONObject(i); 
       String three=jsonObject.optString("3.0"); 
       float f = Float.parseFloat(three); 

      String v1e1 = new BarEntry(Float.parseFloat(three), 0); // 0 

      ` 

錯誤: 致命異常:主要

                    java.lang.NumberFormatException: Invalid float: "" 
                         at java.lang.StringToReal.invalidReal(StringToReal.java:63) 
                         at java.lang.StringToReal.parseFloat(StringToReal.java:308) 
                         at java.lang.Float.parseFloat(Float.java:306) 
+0

請檢查該http://stackoverflow.com/questions/7552660/ java-convert-float-to-string-and-string-to-float –

+10

可能重複的[轉換字符串浮動?](http://stackoverflow.com/questions/8705017/convert-string-to-float) – Prabu

+2

'給錯誤.'哪個錯誤? –

回答

1
String number="3"; 
Float f = Float.valueOf(number); 
0

You should catch NumberFormatException in case of floating number conversion failures.

try{ 
     String number="3"; 
     Float f=Float.parseFloat(number); 
     } 
     catch(NumberFormatException NFE) 
     { 
      System.out.println("NumberFormatException: " + NFE.getMessage()); 
     }