Check if number is decimal

前端 未结 17 1702
生来不讨喜
生来不讨喜 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 14:53

    I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

    function isDecimal($value) 
    {
         return ((float) $value !== floor($value));
    }
    

    I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.

    0 讨论(0)
  • 2020-12-09 14:54

    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.

    0 讨论(0)
  • 2020-12-09 14:57

    You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

    function is_decimal( $val )
    {
        return is_numeric( $val ) && floor( $val ) != $val;
    }
    
    0 讨论(0)
  • 2020-12-09 14:59

    Simplest solution is

    if(is_float(2.3)){
    
     echo 'true';
    
    }
    
    0 讨论(0)
  • 2020-12-09 15:00

    another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)

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

    Maybe try looking into this as well

    !is_int()

    0 讨论(0)
提交回复
热议问题