PHP: Compare floats & why its different to a normal comparison
Comparing two bits of data in PHP is quite simple but there are special occasions when a simple comparison of data needs to be slightly different. One of the common issues is comparing float numbers, a common mistake is comparing two float numbers the same way in which you would compare two integers or two strings.
What does float, double or real number look like?
1.234
1.2e4
7E-10
This is due to how PHP stores float numbers (also known as doubles or real numbers) which gives this type of data a very limited precision resulting in numbers being slightly off, for a more in-depth explanation please read the following article http://php.net/manual/en/language.types.float.php.
This issue only occurs once a calculation is performed on a float number.
The best way of comparing two floats to get an accurate comparison is to convert the value to an alternative data type such as a integer, string or use “bccomp” which allows you to compare 2 float data types together up to the precision you specify (bccomp can also be used to determine which of the two floats is higher or lower).
Read up on bccomp: http://php.net/manual/en/function.bccomp.php
Is Match Comparison
1 2 3 4 5 |
if ( bccomp( 12.498500003 , 12.49850011 , 4 ) == 0 ){ die('These numbers match 100% as we are only using a precision of 4'); die('It compares 12.4985 with 12.4985 and forgets the rest of the number.'); die('A value of 0 was returned by bccomp as the numbers match.'); } |
Greater or Lower Comparison
1 2 3 4 5 6 7 8 9 |
if ( bccomp( 12.482015642 , 12.4895512 , 4 ) == -1 ){ die('bccomp returns -1 because number1 (12.4820) is lower than number2 (12.4895).'); die('Remember a precision of 4 is being used so the rest of the number is ignored.'); } if ( bccomp( 12.4895512 , 12.482015642, 4 ) == 1 ){ die('bccomp returns -1 because number1 (12.4895512) is greater than number2 (12.482015642).'); die('Remember a precision of 4 is being used so the rest of the number is ignored.'); } |