Is it possible to filter the integer with decimal points using filter_var in PHP?
I need to filter the value like this 100.50
using filter_var in PHP.
Now I am using like this
filter_var($_POST['amount'],FILTER_SANITIZE_NUMBER_INT)开发者_如何学Go : '';
And it gives me the result is 10050
.
How can I solve this problem.
Thanks in advance.An integer does not have decimal fractions, so the validation must fail (although I find the sanitation result of 100.50
turning into 10050
pretty bizarre on PHP's end. WTF?).
You would need to use a different filter, e.g. FILTER_VALIDATE_FLOAT
.
List of PHP validate filters
The number 100.50 is not an integer, it is a float. To filter variables that are floats you should use FILTER_SANITIZE_NUMBER_FLOAT
. This will remove all unwanted characters and leave you with a float.
Here is some example code:
$_POST['amount'] = 100.50;
// Use FILTER_FLAG_ALLOW_FRACTION to allow decimal places to remain without being removed
$amount = filter_var($_POST['amount'],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
print $amount;
// When you print it will print out 100.50
Remember this only works if your installed PHP is version 5.2.0 or better.
If you absolutely want to use filter_var because you want to remove all other characters, use FILTER_SANITIZE_NUMBER_FLOAT and then cast to integer.
intval
returns the integer part of your variable (everything without the decimal places).
intval(100.50)
would return 100
. However, I'm not sure if that is what you want.
One should take care when converting decimal stings to floating values. Doing so can result in rounding errors. If you must keep the decimal precision, using preg_replace to remove all characters except for numbers and the period would be a good option.
We need to pass flag in the third parameter of filter_var function as -
print filter_var($_POST['amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
Cheers
精彩评论