PHP:获取小数位数
有没有一种简单的方法来确定PHP中a(n)整数/双精度值的小数位数? (即,不使用explode)
Erwin asked 2020-07-28T21:50:58Z
17个解决方案
72 votes
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
ghostdog74 answered 2020-07-28T21:51:02Z
11 votes
您可以尝试将其强制转换为int,然后从您的数字中减去该数字,然后计算剩余的数字。
Allyn answered 2020-07-28T21:51:22Z
11 votes
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);
}
输出:
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
Kris answered 2020-07-28T21:51:41Z
3 votes
我使用以下方法确定返回的值是否具有任何小数位数(实际的十进制值,而不仅仅是格式化为显示100.00之类的小数):
if($mynum - floor($mynum)>0) {has decimals;} else {no decimals;}
skips answe