Check if number is decimal

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

    if you want "10.00" to return true check Night Owl's answer

    If you want to know if the decimals has a value you can use this answer.

    Works with all kind of types (int, float, string)

    if(fmod($val, 1) !== 0.00){
        // your code if its decimals has a value
    } else {
        // your code if the decimals are .00, or is an integer
    }
    

    Examples:

    (fmod(1.00,    1) !== 0.00)    // returns false
    (fmod(2,       1) !== 0.00)    // returns false
    (fmod(3.01,    1) !== 0.00)    // returns true
    (fmod(4.33333, 1) !== 0.00)    // returns true
    (fmod(5.00000, 1) !== 0.00)    // returns false
    (fmod('6.50',  1) !== 0.00)    // returns true
    

    Explanation:

    fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))

    Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)

    From the PHP docs:

    Operands of modulus are converted to integers (by stripping the decimal part) before processing.

    Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator

提交回复
热议问题