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

后端 未结 4 1034
轮回少年
轮回少年 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 10:57

    You can use a regex to figure out if it has more than 2 decimals:

     0);
        }
    
        $numbers = array(123.456, 123.450, '123.450', 123.45000001, 123, 123.4);
    
        foreach ($numbers as $number) {
            echo $number . ': ' . (doesNumberHaveMoreThan2Decimals($number) ? 'Y' : 'N') . PHP_EOL;
        }
    ?>
    

    Output:

    123.456:      Y
    123.45:       N
    123.450:      N
    123.45000001: Y
    123:          N
    123.4:        N
    

    DEMO

    Regex autopsy (/\.[0-9]{2,}[1-9][0-9]*$/):

    • \. - a literal . character
    • [0-9]{2,} - Digits from 0 to 9 matched 2 or more times
    • [1-9] - A digit between 1 and 9 matched a single time (to make sure we ignore trailing zeroes)
    • [0-9]* - A digit between 0 and 9 matched 0 to infinity times (to make sure that we allow 123.4510 even though it ends with 0).
    • $ - The string MUST end here - nothing else can be between our last match and the end of the string

提交回复
热议问题