downloads | documentation | faq | getting help | mailing lists | reporting bugs | sites | links | my 
search for in the  
view the version of this page
Last updated: Thu, 21 Aug 2003

Floating point numbers

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:

$a = 1.234; 
$b = 1.2e3; 
$c = 7E-10;


LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

Floating point precision

It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999....

This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . ..

So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.

Converting to float

For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information.

add a note add a note User Contributed Notes
Floating point numbers
gallico_ at hotmail dot com
07-Sep-2003 10:34
To complete the thread about testing two floating point numbers for equality, here's the way it works for *every* programming language:

// two fp numbers should be considered equal if their absolute
// difference does not exceed a certain value epsilon:
$epsilon 0.0001// this defines the precision of your comparision
// check their absolute difference
if (abs($one_float $another_float) < $epsilon)
// what to be done in case the numbers are equal goes here
james dot cridland at virginradio dot co dot uk
28-Apr-2003 09:44
The 'floating point precision' box in practice means:

<? echo (69.1-floor(69.1)); ?>
Think this'll return 0.1?
It doesn't - it returns 0.099999999999994

<? echo round((69.1-floor(69.1))); ?>
This returns 0.1 and is the workaround we use.

Note that
<? echo (4.1-floor(4.1)); ?>
*does* return 0.1 - so if you, like us, test this with low numbers, you won't, like us, understand why all of a sudden your script stops working, until you spend a lot of time, like us, debugging it.

So, that's all lovely then.
dev at maintainfit dot com
16-Apr-2003 01:27
I was programming an accounting application in MySql that required me to sum a collection of floats and ensure that they equal zero before commiting a transaction, but as seen above a sum of floats cannot always be trusted (as was my case).  I kept getting a very small remainder (like 1.4512431231e-14).  Since I had used number_format(num,2) to set the precision of the numbers in the database to only two (2) decimal places, when the time comes to calculate the sum I simply multiply every number by ten (10), therby eliminating and decimal places and leaving me with integers to preform my sum.  This worked great.
01-Apr-2003 05:20
In response to "...the author probably knows what they are talking about..." above:

Of course the author knows what they're talking about. The previous poster missunderstood the semantics of the author's example of the decimal representation of 1/3. The author is not suggesting that some property of decimal numbers causes the behaviour, but that the property of finite binary representations of real numbers which does cause the problem is shared by finite decimal representations. To paraphrase, the author is saying "10*(0.1+0.7) gives 7.99999... because of the binary equivalent of the fact that 1/3+2/3 gives 0.99999... when using finite decimal representations (where 1/3 == 0.33333... and 2/3 == 0.66666..., so 1/3+2/3 == (0.33333...)+(0.66666...) == 0.99999... instead of 1)."

The problem occurs with finite representations of real numbers, regardless of base of the number system used.
Theo Diem
27-Mar-2003 02:35
Just to mention ....

$something = "12.20";
$value = (float) $something;

Depending you locale settings (see setlocale) this will return a float number 12.2 or 12 (without decimal part, if you locale uses another symbol than dot for decimal part)

Be aware if u are working with PHP using one locale setting (by setlocale) and a SQL database with other locale ....
Julian Suggate
10-Mar-2003 10:22
Never never never compare floats for equality! Even a >= is asking too much of any binary computer (that's pretty much all of them ;-). It will sometimes work, but the best you can hope for is a subtle bug that will occasionally cause non-deterministic behaviour.

Floats must only ever be used for proper inequalities.
backov at spotbrokers-nospamplz dot com
06-Mar-2003 05:16
I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane.

This test (where var_dump says that $a=0.1 and $b=0.1)

if ($a>=$b) then echo "blah!";

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) then echo "blah!";

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?
04-Mar-2003 07:31
Having had problems with floatval() and doubleval() (on some servers the former doesn't work, on some the latter doesn't), I finally decided to convert variables to floats with this:

$string = '-12.5';
$float = $string + 0.0;
05-Feb-2003 02:49
just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333."

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated.  0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result).  However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.
28-Sep-2002 01:45
much easier:
  e.g. round(3.1415927,2) => 3.14
        round(1092,-2) => 1100
jnm at mormino dot net
09-Aug-2002 03:03
[Editor's note: the contributor did not see number_format(), sprintf() and other similar functions that can accomplish this task.]

I'm sure there is an easier way to float a number to a desired precision, but I couldn't find one.  So, here is a function that floats 1 decimal place.

function float1($val)
    $x = intval(10*$val)/10;
    if ($x == intval($x)) return "".$x.".0";
    else return intval(10*$val)/10;
php at spamcheck dot aerospace dot fries dot net
25-Jul-2002 09:43
An earlier tip is incorrect.

$var = 1.5;
print("round ".round($var).", floor ".floor($var+0.5).", ceil ".ceil($var-0.5)."\n");

round 2, floor 2, ceil 1
you could say,
round($var) == floor($var+0.5) &&
 round($var) == -1*ceil(-1*($var+0.5))
niekomaatjes at hotmail dot com
22-Jun-2002 10:13
If you'd want floor((0.1+0.7)*10) to return 8, you could add a real small fraction to it, like this:
floor((0.1+0.7)*10 + 0.0000001)

This will usually return 8.
flogazo at aon dot at
15-Dec-2001 02:22
NZamani at CyberWorldZ dot de
17-Jun-2001 01:09
A little tip that could help you:

round($var) == floor($var + 0.5) == ceil($var - 0.5)
jeroen at php dot net
24-May-2001 09:13
If you want to round a floating point number to the nearest multiple of some number n, use the following trick:

$rounded = round($number / n) * n

For example, to round 12874.49 to the nearest 100-multiple (i.e. 12900), use
$rounded = round($number / 100) * 100

Use ceil() or floor() if you want to round down/up.

 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat 01 Nov 2003 04:13:36 EST EST