Check if number is decimal

前端 未结 17 1813
生来不讨喜
生来不讨喜 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:06

    If you are working with form validation. Then in this case form send string. I used following code to check either form input is a decimal number or not. I hope this will work for you too.

    function is_decimal($input = '') {
    
        $alphabets = str_split($input);
        $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 
    
        foreach ($alphabets as $key => $alphabet) {
            if (!in_array($alphabet, $find)) {
                return false;
            }
        }
    
        // Check if user has enter "." point more then once.
        if (substr_count($input, ".") > 1) {
            return false;
        }
    
        return true;
    }
    

提交回复
热议问题