Check if number is decimal

前端 未结 17 1703
生来不讨喜
生来不讨喜 2020-12-09 14:53

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?

相关标签:
17条回答
  • 2020-12-09 15:14
       // if numeric 
    
    if (is_numeric($field)) {
            $whole = floor($field);
            $fraction = $field - $whole;
    
            // if decimal            
            if ($fraction > 0)
                // do sth
            else
            // if integer
                // do sth 
    }
    else
    
       // if non-numeric
       // do sth
    
    0 讨论(0)
  • 2020-12-09 15:15

    If all you need to know is whether a decimal point exists in a variable then this will get the job done...

    function containsDecimal( $value ) {
        if ( strpos( $value, "." ) !== false ) {
            return true;
        }
        return false;
    }
    

    This isn't a very elegant solution but it works with strings and floats.

    Make sure to use !== and not != in the strpos test or you will get incorrect results.

    0 讨论(0)
  • 2020-12-09 15:17

    This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.

    /^(\d+)(\.\d+)?$/
    
    0 讨论(0)
  • 2020-12-09 15:18
    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.

    0 讨论(0)
  • 2020-12-09 15:20
    $lat = '-25.3654';
    
    if(preg_match('/./',$lat)) {
        echo "\nYes its a decimal value\n";
    }
    else{
        echo 'No its not a decimal value';
    }
    
    0 讨论(0)
提交回复
热议问题