php 检查整数或浮点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3461693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:51:24  来源:igfitidea点击:

check for integer or float values

php

提问by Asim Zaidi

I have this

我有这个

$number = 0.5

if (is_float($number))
{
  echo 'float';
}
else
{
  echo 'not float';
}

and it echos not float. what could be the reason thanks

它回声不浮动。可能是什么原因谢谢

回答by Artefacto

Probably $numberis actually a string: "0.5".

可能$number实际上是一个字符串:"0.5".

See is_numericinstead. The is_*family checks against the actual type of the variable. If you only what to know if the variable is a number, regardless of whether it's actually an int, a floator a string, use is_numeric.

is_numeric来代替。该is_*系列检查变量的实际类型。如果您只知道变量是否为数字,而不管它实际上是 an int、afloat还是 a string,请使用is_numeric.

If you need it to have a non-zero decimal part, you can do:

如果你需要它有一个非零的小数部分,你可以这样做:

//if we already know $number is numeric...
if ((int) $number == $number) {
    //is an integer
}

回答by Noor

If you are checking just for the .(dot)then you do not need to typecastbut manipulate it as a string with [strpos][1]().

如果您只是检查 ,.(dot)那么您不需要typecast而是将其作为字符串进行操作[strpos][1]()

if (strpos($number,'.') !== false) {

    echo 'true';
}else {
    echo 'false';
}

回答by dale3h

If I understand correctly, using the typecast will allow you to check int and float properly regardless of the machine's locale. However, I could be very wrong...I am not sure if PHP supports decimal locales, such as the comma (,) for certain countries.

如果我理解正确,无论机器的语言环境如何,使用类型转换都可以让您正确检查 int 和 float。但是,我可能是非常错误的...我不确定 PHP 是否支持十进制语言环境,例如某些国家/地区的逗号 (,)。