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 (
I know, its an old question, but why not just do:
function onlyDecimals($number, $maxDecimalPlaces = 2) {
return $amount == number_format($amount, $maxDecimalPlaces, ".", "");
}
See example and tests: http://sandbox.onlinephpfunctions.com/code/e68143a9ed0b6dfcad9ab294c44fa7e802c39dd0
You can use a regex to figure out if it has more than 2 decimals:
<?php
function doesNumberHaveMoreThan2Decimals($number) {
return (preg_match('/\.[0-9]{2,}[1-9][0-9]*$/', (string)$number) > 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 stringYou 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 "<br/>";
}
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.
You could use a regex:
$number = 1.12; //Don't match
$number = 1.123; //Match
$number = 1.1234; //Match
$number = 1.123; //Match
if (preg_match('/\.\d{3,}/', $number)) {
# Successful match
} else {
# Match attempt failed
}