我在这里遇到的一个有趣的问题,通常我只是根据我的需求分别用数字向上/向下舍入,但今天我发现自己必须非常具体。我正在从事一个有许多点版本的项目。它是一个基于 Web 的应用程序,带有客户端应用程序,其中一项新功能即将推出,如果您的客户端版本为 2.3 或更高版本,那么新功能在应用程序中可用,如果没有,那么它需要隐藏起来。所以我在努力
if($version >= 2.3){/*code to show*/}
这似乎不适用于基于十进制的数字,是否有人知道的解决方法不涉及在任一方向上四舍五入?
对于
这个特定问题,有一个叫做 version_compare()
的 PHP 函数。
if( version_compare( $version, 2.3, '>=') >= 0)
版本比较听起来很酷,但你确实需要使用这种格式。
如果您没有使用"PHP 标准化"版本号,则可以使用 bcmath 的bccomp
来比较 2 个十进制数字。
http://www.php.net/manual/en/function.bccomp.php
我知道
回答这个问题可能为时已晚,但这是我使用的功能:
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;
}
}
}