javastring是数字
① java中String字符串转化为数字
在java中,要将字符串转换为数字,使用基本数据类型的parseXXX方法,比如:Integer.parseInt()方法转换为整数;Float.parseFloat()方法转换为浮点小数,其它都类似的
举例:
String s = "11";
System.out.println("字符串转换为整数的结果为:" + Integer.parseInt(s));
System.out.println("字符串转换为浮点数的结果为:" + Float.parseFloat(s));
输出结果为:
字符串转换为整数的结果为:11
字符串转换为浮点数的结果为:11.0
② java判断string是不是数字
java中判断字符串是否为数字的方法:
1.用JAVA自带的函数
public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
上面三种方式中,第二种方式比较灵活。
③ java中,String字符串转化为数字
java中,String字符串转化为数字的方法有:
1、转化为整型数字
(1)Integer.parseInt(String s) ,代码示例如下:
public class Test {
public static void main(String args[]){
String s = "123";
int num = Integer.parseInt(str);
int sum = num + 100;
System.out.println("Result is: "+sum); // 输出结果为:Result is: 223
}}