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 (
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