Check if number is decimal

Viewed 132374

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)

Any reliable way to do this?

19 Answers

is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.

the easy way to find either posted value is integer and float so this will help you

$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
    echo 'success';
}
else
{
   echo 'unsuccess';
}

if you give 10 or 10.5 or 10.0 the result will be success if you define any character or specail character without dot it will give unsuccess

How about (int)$value != $value? If true it's decimal, if false it's not.

I can't comment, but I have this interesting behaviour. (tested on v. 7.3.19 on a website for php testing online)

If you multiply 50 by 1.1 fmod gives different results than expected. If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.

$price = 50;
$price = $price * 1.1; 

if(strpos($price,".") !== false){
    echo "decimal";
}else{
    echo "not a decimal";
}

echo '<br />';

if(fmod($price, 1) !== 0.00){
    //echo fmod($price, 1);
    echo "decimal";
} else {
    echo "not a decimal";
}//end if
function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.

Related