当前位置:首页 » 编程语言 » javastring是数字

javastring是数字

发布时间: 2023-05-21 22:57:45

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

}}

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:712
制作脚本网站 发布:2025-10-20 08:17:34 浏览:974
python中的init方法 发布:2025-10-20 08:17:33 浏览:686
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:837
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:743
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:1085
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:314
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:194
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:882
python股票数据获取 发布:2025-10-20 07:39:44 浏览:840