PHP: How to check if a number has more than two decimals

后端 未结 4 1020
轮回少年
轮回少年 2021-01-21 10:12

I\'m trying to pick out numbers with more than two decimals (more than two digits after the decimal separator). I cant\'t figure out why this doesn\'t work:

if (         


        
4条回答
  •  天命终不由人
    2021-01-21 11:00

    You could use the following function (works with negative numbers, too):

    function decimalCheck($num) {
        $decimals = ( (int) $num != $num ) ? (strlen($num) - strpos($num, '.')) - 1 : 0;
        return $decimals >= 2;
    }
    

    Test cases:

    $numbers = array(
        32.45,
        32.44,
        123.21,
        21.5454,
        1.545400,
        2.201054,
        0.05445,
        32,
        12.0545400,
        12.64564,
        -454.44,
        -0.5454
    );
    foreach ($numbers as $number) {
        echo $number. "\t : \t";
        echo (decimalCheck($number)) ? 'true' : 'false';
        echo "
    "; }

    Output:

    32.45    :  true
    32.44    :  true
    123.21   :  true
    21.5454  :  true
    1.5454   :  true
    2.201054 :  true
    0.05445  :  true
    32       :  false
    12.05454 :  true
    12.64564 :  true
    -454.44  :  true
    -0.5454  :  true
    

    Demo.

提交回复
热议问题