开发者

Comparing double decimal number

开发者 https://www.devze.com 2023-02-16 17:07 出处:网络
I want to开发者_JAVA技巧 compare version numbers of apps/software which sometimes may have two decimal points such as:

I want to开发者_JAVA技巧 compare version numbers of apps/software which sometimes may have two decimal points such as:

1.0
1.1
1.0.01
1.0.1
2.0
2.5
3.0

etc. etc..

What would be the correct way of comparing these numbers?

I tried a this but get an error:

Parse error: syntax error, unexpected T_DNUMBER in /home/videocoo/public_html/dev/vc-admin/test_cmp.php on line 2

$a = 1.2.11;
$b = 1.2.0;

if($a > $b){
    print"<br />a is greater";
} else {
    print"<br />b is greater";
}

Is it incorrect to make the numbers into a string, wrapping them in double quotes? It seemed to give the right comparison every time I tested different numbers. Thanks!


The function you are looking for is version_compare() PHP Reference

<?php
$versionA = '1.0.1';
$versionB = '1.0.2';

if (version_compare($versionA, $versionB) >= 0) {
    echo 'Version B is equal to or greater than Version A';
}

if (version_compare($versionA, $versionB, '<')) {
    echo 'Version A is less than Version B';
}
?>


Comparing the version numbers as strings won't work: check 1.9 vs. 1.11. You can use version_compare instead: http://php.net/manual/en/function.version-compare.php.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号