java判断字符串是否为数字或小数

1.判断是否费数字


  
  
  1. public static boolean isNumericInt (String str){
  2. Pattern pattern = Pattern.compile( "[0-9]*");
  3. return pattern.matcher(str).matches();
  4. }

2.判断字符串是否为整数或者小数 方法一


  
  
  1. public static boolean isNumeric (String str){
  2. Pattern pattern = Pattern.compile( "[0-9]*\\.?[0-9]+");
  3. Matcher isNum = pattern.matcher(str);
  4. if (!isNum.matches()) {
  5. return false;
  6. }
  7. return true;
  8. }

判断字符串是否为整数或者小数 方法二


  
  
  1. public static boolean isNumeric (String str){
  2. Pattern pattern = Pattern.compile( "[0-9]*");
  3. if(str.indexOf( ".")> 0){ //判断是否有小数点
  4. if(str.indexOf( ".")==str.lastIndexOf( ".") && str.split( "\\.").length== 2){ //判断是否只有一个小数点
  5. return pattern.matcher(str.replace( ".", "")).matches();
  6. } else {
  7. return false;
  8. }
  9. } else {
  10. return pattern.matcher(str).matches();
  11. }
  12. }

3.java 判断一个字符串是不是整数、浮点数、科学计数(正则表达式)


  
  
  1. public static boolean isNumeric (String str) {
  2. if ( null == str || "".equals(str)) {
  3. return false;
  4. }
  5. String regx = "[+-]*\\d+\\.?\\d*[Ee]*[+-]*\\d+";
  6. Pattern pattern = Pattern.compile(regx);
  7. boolean isNumber = pattern.matcher(str).matches();
  8. if (isNumber) {
  9. return isNumber;
  10. }
  11. regx = "^[-\\+]?[.\\d]*$";
  12. pattern = Pattern.compile(regx);
  13. return pattern.matcher(str).matches();
  14. }

如果以上方法返回的值为true,则可以进行下一步操作,比如将字符串转化为整数: Integer.parseInt(str),或者将字符串转化为小数: Double.valueOf(str)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值