用JAVA自带的函数
public static boolean isNumericZidai(String str) { for (int i = 0; i <p>其中Character.isDigit方法:确定或判断指定字符是否是一个数字。</p><p>测试方法:</p><pre class="brush:php;toolbar:false"> public static void main(String[] args) { double aa = -19162431.1254; String a = "-19162431.1254"; String b = "-19162431a1254"; String c = "中文"; System.out.println(isNumericzidai(Double.toString(aa))); System.out.println(isNumericzidai(a)); System.out.println(isNumericzidai(b)); System.out.println(isNumericzidai(c)); }
结果显示:
false false false false
这种方法显然不能判断 负数。
用正则表达式
/** * 匹配是否为数字 * @param str 可能为中文,也可能是-19162431.1254,不使用BigDecimal的话,变成-1.91624311254E7 * @return * @date 2016年11月14日下午7:41:22 */ public static boolean isNumeric(String str) { // 该正则表达式可以匹配所有的数字 包括负数 Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?"); String bigStr; try { bigStr = new BigDecimal(str).toString(); } catch (Exception e) { return false;//异常 说明包含非数字。 } Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配 if (!isNum.matches()) { return false; } return true; }
使用org.apache.commons.lang
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知识请关注java基础教程。
The above is the detailed content of How to determine whether a string is a number in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
