php大于十进制数字没有圆,ceil,floor

时间:2012-06-26 19:29:47

标签: php

有趣的问题我在这里,通常我只是根据我的需要用数字向上/向下舍入,但今天我发现自己必须非常具体。我正在开发一个有很多点版本的项目。它是一个基于Web的应用程序,带有客户端应用程序,如果您的客户端版本为2.3或更高版本,则会在软件中出现新功能,然后在应用程序中提供新功能,如果没有,则需要隐藏起来。所以我在尝试

if($version >= 2.3){/*code to show*/}

似乎没有使用基于小数的数字,是否有任何人都知道的解决方法不涉及在任何一个方向上舍入它?

3 个答案:

答案 0 :(得分:8)

这个特定问题有一个名为version_compare()的PHP函数。

if( version_compare( $version, 2.3, '>=') >= 0) 

答案 1 :(得分:0)

版本比较听起来很酷,但您确实需要使用该格式。

如果您不使用“PHP标准化”版本号,则可以使用bcmath的bccomp来比较2个十进制数。

http://www.php.net/manual/en/function.bccomp.php

答案 2 :(得分:0)

我知道回答这个问题可能会迟到,但这是我使用的功能:

if(!function_exists('CompareVersion')){
    function CompareVersion($v1='', $v2='', $s='>'){
        #   We delete all characters except numbers 0-9
        $regex = '/[^0-9]/';
        $v1 = preg_replace($regex, '', $v1);
        $v2 = preg_replace($regex, '', $v2);

        #   Wewill get the length of both string
        $lgt1 = strlen($v1);
        $lgt2 = strlen($v2);

        #   We will make sure that the length is the same by adding zeros at the end
        #   Example: 1031 and 30215 - 1031 is smaller then 1031 become 10310
        if($lgt2 > $lgt1){
            $v1 = str_pad($v1, $lgt2, 0, STR_PAD_RIGHT);
        } elseif($lgt1 > $lgt2){
            $v2 = str_pad($v2, $lgt1, 0, STR_PAD_RIGHT);
        }

        #   We remove the leading zeros
        $v1 = ltrim($v1, 0);
        $v2 = ltrim($v2, 0);

        #   We return the result
        switch($s){
            case '>':   return $v1 > $v2;
            case '>=':  return $v1 >= $v2;
            case '<':   return $v1 < $v2;
            case '<=':  return $v1 <= $v2;
            case '=':
            case '==':  return $v1 == $v2;
            case '===': return $v1 === $v2;
            case '<>':
            case '!=':  return $v1 != $v2;
            case '!==': return $v1 !== $v2;
        }
    }
}