php中的float怎么用,PHP is_float 用法 手册 | 示例代码

Boylett's solution is elegant (http://php.net/manual/en/function.is-float.php#85848), but won't work for long float's or variables that are not explicitly type of 'string' or for long floats that are encased in quotes, making it a string that will be truncated/rounded when cast to a float.  So, further logic must be completed to test for the case.  Take the following example:

functiontest_float($test) {

if (!is_scalar($test)) {returnfalse;}$type=gettype($test);

if ($type==="float") {

returntrue;

} else {

returnpreg_match("/^\d+\.\d+$/",$test) ===1;

}

}

}$test="3.14159265358979323846264338g32795";var_dump($test);var_dump((float)$test);var_dump($test== (string)(float)$test);var_dump(test_float($test));?>

Will produce (32-bit):

string(34) "3.14159265358979323846264338g32795"

float(3.1415926535898)

bool(false)

bool(false)

So far, so good, right?  Yeah, but it's misleading, because the string is so long, that when it's converted to a float, it won't be equivalent to the comparison of the value being cast back into a string .  So the aforementioned short function works.  Look at this next example:

$test =3.1415926535897932384626433832795;

var_dump($test);var_dump((float)$test);var_dump($test== (string)(float)$test);var_dump(test_float($test));

?>

Will produce (32-bit):

float(3.1415926535898)

float(3.1415926535898)

bool(false)

bool(true)

Why is it not working now, but the value is truly a float?  Same reasoning as mentioned before.  The float is so long that it's truncated/rounded and doesn't match the comparison being done with the short-hand function.

So, as you can see, more logic should be applied to the variable you're testing.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值