Search code examples
phpfloating-pointmoney-format

Check if variable is float with max 2 decimal places


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.


Solution

  • 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.