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
}}