Check if number is decimal

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

提交回复
热议问题