您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)java判斷字符串是否為數(shù)字的方法,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
用JAVA自帶的函數(shù)
public static boolean isNumericZidai(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; }
其中Character.isDigit方法:確定或判斷指定字符是否是一個(gè)數(shù)字。
測(cè)試方法:
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)); }
結(jié)果顯示:
false false false false
這種方法顯然不能判斷 負(fù)數(shù)。
用正則表達(dá)式
/** * 匹配是否為數(shù)字 * @param str 可能為中文,也可能是-19162431.1254,不使用BigDecimal的話,變成-1.91624311254E7 * @return * @date 2016年11月14日下午7:41:22 */ public static boolean isNumeric(String str) { // 該正則表達(dá)式可以匹配所有的數(shù)字 包括負(fù)數(shù) Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?"); String bigStr; try { bigStr = new BigDecimal(str).toString(); } catch (Exception e) { return false;//異常 說(shuō)明包含非數(shù)字。 } 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
關(guān)于java判斷字符串是否為數(shù)字的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。