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

Greater or Lower Comparison

Leave a Reply

5 × 1 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Next ArticlePHP: Get Page URLs / Directoy Listings