简体   繁体   English

检查数字是否在 PHP 中浮动

[英]checking if a number is float in PHP

This is really weird.这真的很奇怪。 I have this piece of code.我有这段代码。

$rewardAmt = $amt;
if(is_float($rewardAmt)){
      print_r("is float");die;
} else {
      print_r("is not float"); die;
}

value of $amt is 0.01. $amt 的值为 0.01。 But it is going into else condition.但它正在进入其他条件。 So I did a var_dump of $amt.所以我做了一个 $amt 的 var_dump。 it says string(4) So I decided to typecast $amt它说 string(4) 所以我决定输入 $amt

   $rewardAmt = (float)$amt;

But the problem with this is even if the value of $amt is 1, it still gets typecast to float and goes into if condition, which shouldn't happen.但是这样做的问题是,即使 $amt 的值为 1,它仍然会被类型转换为浮动并进入 if 条件,这是不应该发生的。 Is there any other way to do this ?有没有其他方法可以做到这一点? Thanks谢谢

Use filter_var() with FILTER_VALIDATE_FLOAT使用filter_var()FILTER_VALIDATE_FLOAT

if (filter_var($amount, FILTER_VALIDATE_FLOAT))
{
     // good
}

If you change the first line to如果您将第一行更改为

$rewardAmt = $amt+0;

$rewardAmt should be cast to a number. $rewardAmt 应该被转换为一个数字。

You can use the unary + operator, which will cast the string to the appropriate type ( int or float ), and then test the resulting data type with is_float :您可以使用一元+运算符,它将字符串转换为适当的类型( intfloat ),然后使用is_float测试结果数据类型:

$s = "3.00";
$n = +$s;
var_dump( $n ); // float(3)
var_dump( is_float($n) ); // true


$s = "3";
$n = +$s;
var_dump( $n ); // int(3)
var_dump( is_float($n) ); // false

You can check this by您可以通过以下方式检查

$float = floatval($num); //Convert the string to a float
if($float && intval($float) != $float) // Check if the converted int is same as the float value...
{
    // $num is a float
}else{
    // $num is an integer
}

As suggested in the documentation of is_float function :正如is_float 函数文档中所建议

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric() .注意:要测试变量是数字还是数字字符串(例如表单输入,它始终是字符串),您必须使用is_numeric()

The answer is using is_numeric() and not is_float().答案是使用is_numeric()而不是 is_float()。 This works also if the number tested is "0" or 0.如果测试的数字是“0”或 0,这也有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM