创建一个函数,使其接收一个字符串并判断该字符串是否为数字。
#include
#include
int isNumeric (const char * s)
{
if (s == NULL || *s == '\0' || isspace(*s))
return 0;
char * p;
strtod (s, &p);
return *p == '\0';
}
#include // for istringstream
using namespace std;
bool isNumeric( const char* pszInput, int nNumberBase )
{
istringstream iss( pszInput );
if ( nNumberBase == 10 )
{
double dTestSink;
iss >> dTestSink;
}
else if ( nNumberBase == 8 || nNumberBase == 16 )
{
int nTestSink;
iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
}
else
return false;
// was any input successfully consumed/converted?
if ( ! iss )
return false;
// was all the input successfully consumed/converted?
return ( iss.rdbuf()->in_avail() == 0 );
}
bool isNumeric( const char* pszInput, int nNumberBase )
{
string base = "0123456789ABCDEF";
string input = pszInput;
return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
}
bool isNumeric(const std::string& input) {
return std::all_of(input.begin(), input.end(), ::isdigit);
}
//.Net 2.0+
public static bool IsNumeric(string s)
{
double Result;
return double.TryParse(s, out Result); // TryParse routines were added in Framework version 2.0.
}
string value = "123";
if (IsNumeric(value))
{
// do something
}
//.Net 1.0+
public static bool IsNumeric(string s)
{
try
{
Double.Parse(s);
return true;
}
catch
{
return false;
}
}
import "strconv"
func IsNumeric(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
public boolean isNumeric(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (NumberFormatException e) {
// s is not numeric
return false;
}
}
以上方式因为异常处理有巨大的性能损耗,可用以下四种方式代替。
检查字符串中的每个字符,此方式只适用于整数。
private static final boolean isNumeric(final String s) {
if (s == null || s.isEmpty()) return false;
for (int x = 0; x < s.length(); x++) {
final char c = s.charAt(x);
if (x == 0 && (c == '-')) continue; // negative
if ((c >= '0') && (c <= '9')) continue; // 0 - 9
return false; // invalid
}
return true; // valid
}
使用正则表达式(推荐)。
public static boolean isNumeric(String inputData) {
return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}
使用java.text.NumberFormat中对象的位置解析器(更可靠的解决方案)。 如果解析后,解析位置是在字符串的结尾则整个字符串是一个数字。
public static boolean isNumeric(String inputData) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(inputData, pos);
return inputData.length() == pos.getIndex();
}
使用java.util.Scanner。
public static boolean isNumeric(String inputData) {
Scanner sc = new Scanner(inputData);
return sc.hasNextInt();
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var value = "123.45e7"; // Assign string literal to value
if (isNumeric(value)) {
// value is a number
}
//Or, in web browser in address field:
// javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}
// version 1.1
fun isNumeric(input: String): Boolean =
try {
input.toDouble()
true
} catch(e: NumberFormatException) {
false
}
fun main(args: Array<String>) {
val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
}
输出:
152 is numeric
-3.1415926 is numeric
Foo123 is not numeric
-0 is numeric
456bar is not numeric
1.0E10 is numeric
$string = '123';
if(is_numeric(trim($string))) {
}
?>
简单形式(整数/浮点数)
def is_numeric(s):
try:
float(s)
return True
except (ValueError, TypeError):
return False
is_numeric('123.0')
更简化(整数)
'123'.isdigit()
一般形式(二进制/十进制/十六进制/数字文本)
def is_numeric(literal):
"""Return whether a literal can be parsed as a numeric value"""
castings = [int, float, complex,
lambda s: int(s,2), #binary
lambda s: int(s,8), #octal
lambda s: int(s,16)] #hex
for cast in castings:
try:
cast(literal)
return True
except ValueError:
pass
return False
def is_numeric?(s)
begin
Float(s)
rescue
false # not numeric
else
true # numeric
end
end
更紧凑的形式
def is_numeric?(s)
!!Float(s) rescue false
end