php - 整数或小数

标签 php

我正在寻找一个函数来测试整数是否是整数。 到目前为止我已经得到了这个:

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/

相关文章:

基于条件的 PHP 常量声明

php - 我应该实现自己的 CMS 吗?

php - MySQL查询没有返回结果

php - 将单值 getJSON 从 php 转换为 JavaScript 变量

php - 从 WordPress 中的 URL 中提取参数

php - 如何使用input type=file上传json文件

php - Codeigniter 中的分页 ajax,从数据库加载数据 otomatis

php - 如何在 PhpStorm 的测试/目录中生成测试?

php - 按降序对表记录进行排序 - symfony

php - 如何处理一个大的 mySQL 树