SomeRandomDude
SomeRandomDude

Reputation: 193

Comparing double decimal number

I want to 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!

Upvotes: 3

Views: 1977

Answers (2)

Luke Stevenson
Luke Stevenson

Reputation: 10341

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';
}
?>

Upvotes: 5

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

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.

Upvotes: 2

Related Questions