Java中如何将字符串转换为float
时间:2020-01-09 10:35:29 来源:igfitidea点击:
在java要将String转换为float,可以使用以下选项之一
1Float.parseFloat(String str)–返回一个新的float,该float初始化为指定String表示的值。
2Float.valueOf(String s)–返回一个Float对象,其中保存由参数字符串s表示的float值。
如我们所见,parseFloat()方法返回一个float基本类型,其中valueValue()方法返回一个Float对象。
Java示例,使用Float.parseFloat将String转换为float
public class StringToFloat {
public static void main(String[] args) {
String str = "56.45f";
try{
float f = Float.parseFloat(str);
System.out.println("value - " + f);
// can be used in arithmetic operations now
System.out.println(f+"/3 = " + f/3);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
throw exp;
}
}
}
输出:
value - 56.45 56.45/3 = 18.816668
对于浮点数,我们可以使用" f"或者" F"(偶数d或者D表示双精度),因此这样的字符串–" 56.45f"在转换时不会导致NumberFormatException。但是使用" 56.45c"之类的其他字母会抛出异常。
Java示例,使用Float.valueOf将String转换为float
public class StringToFloat {
public static void main(String[] args) {
String str = "-55.67456";
try{
Float f = Float.valueOf(str);
System.out.println("value- " + f);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
throw exp;
}
}
}
输出:
value- -55.67456
NumberFormatException
在Java中将字符串转换为float时,如果传递了无效的数字字符串进行转换,则会引发NumberFormatException。
public class StringToFloat {
public static void main(String[] args) {
String str = "43g";
try{
Float f = Float.valueOf(str);
System.out.println("value- " + f);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
throw exp;
}
}
}
输出:
Error in conversion For input string: "43g" Exception in thread "main" java.lang.NumberFormatException: For input string: "43g" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at sun.misc.FloatingDecimal.parseFloat(Unknown Source) at java.lang.Float.parseFloat(Unknown Source) at java.lang.Float.valueOf(Unknown Source) at com.theitroad.programs.StringToFloat.main(StringToFloat.java:8)

