gho*_*g74 74
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
Run Code Online (Sandbox Code Playgroud)
All*_*lyn 11
您可以尝试将其转换为int,从您的数字中减去它,然后计算剩下的数量.
Kri*_*ris 11
function numberOfDecimals($value)
{
if ((int)$value == $value)
{
return 0;
}
else if (! is_numeric($value))
{
// throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
return false;
}
return strlen($value) - strrpos($value, '.') - 1;
}
/* test and proof */
function test($value)
{
printf("Testing [%s] : %d decimals\n", $value, numberOfDecimals($value));
}
foreach(array(1, 1.1, 1.22, 123.456, 0, 1.0, '1.0', 'not a number') as $value)
{
test($value);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Testing [1] : 0 decimals
Testing [1.1] : 1 decimals
Testing [1.22] : 2 decimals
Testing [123.456] : 3 decimals
Testing [0] : 0 decimals
Testing [1] : 0 decimals
Testing [1.0] : 0 decimals
Testing [not a number] : 0 decimals
Run Code Online (Sandbox Code Playgroud)
更少的代码:
$str = "1.1234567";
echo strpos(strrev($str), ".");
Run Code Online (Sandbox Code Playgroud)