我正在寻找一个函数来测试整数是否是整数。 到目前为止我已经得到了这个:
if (is_numeric($answer3)) {
echo "Is triangular\n";
} else {
echo "Is not triangular\n";
}
但这总是返回“Is triangular”,即使 $answer3 是小数。
如何测试一个整数是否有小数?
最佳答案
is_numeric考虑到 float 是数字, float 也会返回 true
Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.
您可以尝试 is_float(),但如果输入是字符串,则它将不起作用。
var_dump( is_float( '23.5' ) ); // return false
因此,如果您正在处理数字的字符串表示形式,那么只需查找 。
if ( strpos( $answer3, '.' ) === false )
如果需要,您可以添加 is_numeric
// Make sure its numeric and has no decimal point
if ( is_numeric( $answer3 ) && strpos( $answer3, '.' ) === false )
关于php - 整数或小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11041590/