当前位置:首页 » 编程语言 » 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

}}

热点内容
如何安排资产配置 发布:2025-07-15 09:33:24 浏览:906
更新传送服务器目的地址失败 发布:2025-07-15 09:27:05 浏览:484
c语言else的用法 发布:2025-07-15 09:19:54 浏览:119
tnt苹果核安卓怎么加好友 发布:2025-07-15 09:05:15 浏览:239
年轻人运行内存为什么比安卓好 发布:2025-07-15 08:52:03 浏览:515
怎么配置组策略 发布:2025-07-15 08:52:02 浏览:246
pythonjson格式 发布:2025-07-15 08:42:54 浏览:678
医院药房要什么配置 发布:2025-07-15 08:29:55 浏览:666
编程说明书 发布:2025-07-15 08:16:39 浏览:761
android请求超时 发布:2025-07-15 07:56:57 浏览:530