PHP:获取小数位数

Erw*_*win 45 php decimal

是否有一种直接的方法来确定PHP中(n)整数/双精度值中的小数位数?(即不使用explode)

gho*_*g74 74

$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
Run Code Online (Sandbox Code Playgroud)

  • 这对于在表示为字符串时转换为科学记数法的极大或极小的浮点数不起作用. (7认同)
  • 例如:`var_dump((string)(0.00000000000012));`outputs`tring(7)"1.2E-13"` (4认同)
  • @GordonM你可以用number_format来解决这个问题:`$ str = rtrim(number_format($ value,14 - log10($ value)),'0');`.14基于PHP中浮点数的最大精度; 如果你在浮点数上做一些数学运算,可能需要减少一点(特别是如果它是通过减去两个更大的数字得到的). (4认同)
  • 如果使用大量数字,则减去1可能更有效,而不是获取子字符串:strlen(strrchr($ str,".")) - 1; (3认同)

All*_*lyn 11

您可以尝试将其转换为int,从您的数字中减去它,然后计算剩下的数量.

  • 在我看来非常好的安装,如果我是对的你必须这样:`echo strlen($ num-(int)$ num)-2;` (3认同)
  • 如果是负值,将返回错误的答案. (2认同)
  • `$decimals = ( (int) $num != $num ) ? (strlen($num) - strpos($num, '.')) - 1 : 0; ` 也适用于负数。 (2认同)

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)

  • 请注意,php 将源代码中的文字 1.0 解释为整数,因此当转换为字符串时,它没有小数。(即使你在声明时将它转换为浮动,所以 `$variable = (float)1.0;` *** 不起作用***) (2认同)
  • 这不适用于非常小或非常大的浮动,当转换为字符串时,这些浮动输出为科学记数法.var_dump(strval(1/1000000)); (2认同)

Mo *_*ami 5

更少的代码:

$str = "1.1234567";
echo strpos(strrev($str), ".");
Run Code Online (Sandbox Code Playgroud)

  • 聪明的。仅供参考,如果数字没有小数点,“strpos”将返回“false”而不是“0” (2认同)
  • @andrewtweber 更新了:) (2认同)