is_numeric
is_numeric(mixed $value): bool
检测变量是否为数字或数字字符串。
C C23
C23
#include <stdio.h>
#include <stdlib.h>
static int is_numeric(const char *s) {
char *end;
(void)strtod(s, &end);
return *s != '\0' && *end == '\0';
}
int main(void) {
printf("%d %d %d\n", is_numeric("42"), is_numeric("1e3"), is_numeric("abc"));
return 0;
}
输出
1 1 0
C++ C++26
C++26
#include <iostream>
#include <string>
static bool is_numeric(const std::string &s) {
try {
(void)std::stod(s);
return true;
} catch (const std::exception &) {
return false;
}
}
int main() {
std::cout << is_numeric("42") << " " << is_numeric("1e3") << " " << is_numeric("abc") << "\n";
return 0;
}
输出
1 1 0
C# v11.0.100
v11.0.100
static bool IsNumeric(string s) => double.TryParse(s, out _);
Console.WriteLine($"{IsNumeric("42")} {IsNumeric("1e3")} {IsNumeric("abc")}");
输出
True True False
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strconv"
)
func isNumeric(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
func main() {
fmt.Println(isNumeric("42"), isNumeric("1e3"), isNumeric("abc"))
}
输出
true true false
Java v27.0.1
v27.0.1
public class Main {
private static boolean isNumeric(String s) {
try {
Double.parseDouble(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(isNumeric("42") + " " + isNumeric("1e3") + " " + isNumeric("abc"));
}
}
输出
true true false
JavaScript v26.13.1
v26.13.1
function isNumeric(v) {
return v !== "" && Number.isFinite(Number(v));
}
console.log([isNumeric(42), isNumeric("1e3"), isNumeric("abc")]);
输出
[ true, true, false ]
PHP v8.6.0
v8.6.0
echo json_encode([is_numeric(42), is_numeric("1e3"), is_numeric("abc")]);
输出
[true,true,false]
Python v3.15.2
v3.15.2
def is_numeric(value):
try:
float(value)
return True
except (TypeError, ValueError):
return False
print([is_numeric(42), is_numeric("1e3"), is_numeric("abc")])
输出
[True, True, False]
Rust v1.99.1
v1.99.1
fn is_numeric(s: &str) -> bool {
s.parse::<f64>().is_ok()
}
fn main() {
println!("{} {} {}", is_numeric("42"), is_numeric("1e3"), is_numeric("abc"));
}
输出
true true false
TypeScript v26.13.1
v26.13.1
function isNumeric(v: unknown): boolean {
return v !== "" && Number.isFinite(Number(v));
}
console.log([isNumeric(42), isNumeric("1e3"), isNumeric("abc")]);
输出
[ true, true, false ]
语言差异说明
C:strtod 解析前缀后残留字符,须检查 end 保证整串都是数字。
C++:std::stod 解析前缀后残留字符,须检查异常保证整串都是数字。
C#:用 double.TryParse。
Go:用 strconv.ParseFloat。
Java:用 Double.parseDouble + 异常。
JavaScript:无内置,用 Number.isFinite(Number(v))(注意 Number(null)、空串等边角需自行排除)。
PHP:is_numeric 接受 int/float 与科学计数法、十六进制等形式的数字字符串。
Python:主流等价做法是「尝试解析整串」——手写 try-float。
Rust:用 str::parse::<f64>()。
TypeScript:同 JS,Number.isFinite(Number(v))。