Check if variable is float with max 2 decimal places

3.2k Views Asked by At

I have user input in a script - $_POST['money'] and I want to confirm that it is infact a float of 2 decimal places.

What I was planning would be $money = (float)@$_POST['money'], in this case it would set $money to zero if a non number was entered. But the case may occur when the user enters something like 5.234, in this case I would also want money set at zero.

I don't want to something tricky with explode or something like that, I was hoping there is an efficient way of doing this.

An integer is also fine, because it's a valid amount.

2

There are 2 best solutions below

3
On BEST ANSWER

I've chosen to use this code:

$money = (float)(@$_POST['money'] / 0.01) <> (int)(@$_POST['money'] / 0.01) ? 0 : (float)@$_POST['money'];

If you have a better solution please post.

1
On

check here:

http://php.net/manual/ro/function.is-float.php

and here

http://php.net/manual/en/function.number-format.php

or use this function

function is_deccount($number,$decimal=2){
    $m_factor=pow(10,$decimal);
    if((int)($number*$m_factor)==$number*$m_factor)
        return true;
    else
        return false;
}