PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Les chaînes de caractères> <Les entiers
Last updated: Fri, 10 Oct 2008

view this page in

Nombres décimaux

Les nombres décimaux, (aussi connus comme nombres à virgule flottante, "floats", "doubles", ou "real numbers") peuvent être spécifiés en utilisant les syntaxes suivantes :

<?php
$a 
1.234;
$b 1.2e3;
$c 7E-10;
?>

Formellement :

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

La taille d'un nombre à virgule flottante est dépendant de la plate-forme, cependant, un nombre maximal de ~1.8e308 avec une précision sur 14 chiffres est une valeur commune (format 64 bits IEEE).

Avertissement

Précision des nombres décimaux

Typiquement, une simple fraction décimale comme 0.1 ou 0.7 ne peut être convertie en sa représentation binaire interne sans perte de précision. Ceci peut porter à confusion : par exemple, floor((0.1+0.7)*10) retournera 7 au lieu de 8 comme cela pourrait se prévoir, car la représentation interne serait quelque chose comme 7.9.

Ceci est dû au fait qu'il est impossible d'exprimer quelques fractions en une notation décimale avec une infinité de chiffres. Actuellement, 1/3, en décimal, devient 0.3.

Ainsi, ne faite jamais confiance aux derniers chiffres d'un nombre décimal, mais aussi, ne comparez jamais l'égalité de 2 nombres décimaux. Si vous avez besoin d'une haute précision, les fonctions mathématiques de précision et les fonctions gmp sont disponibles.

Conversion en un nombre décimal

Pour plus d'informations sur la conversion de chaînes en nombres décimaux , voir la section sur la conversion de chaînes en nombres décimaux. Pour les valeurs d'autres types, la conversion est effectuée en convertissant tout d'abord la valeur en un entier, puis, en nombre à virgule flottante. Voir la section sur la conversion en entier pour plus d'informations. Depuis PHP 5, une notice est émise si un objet est converti en nombre à virgule flottante.



Les chaînes de caractères> <Les entiers
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
Nombres décimaux
an dot kovacs at gmail dot com
09-Jun-2008 07:59
Converting IEEE754 binary representation to php float:

function bin2float ($bin) {
    if((ord($bin[0])>>7)==0) $sign=1;
    else $sign=-1;
    if((ord($bin[0])>>6)%2==1) $exponent=1;
    else $exponent=-127;
    $exponent+=(ord($bin[0])%64)*2;
    $exponent+=ord($bin[1])>>7;
   
    $base=1.0;
    for($k=1;$k<8;$k++) {
     $base+=((ord($bin[1])>>(7-$k))%2)*pow(0.5,$k);
    }
    for($k=0;$k<8;$k++) {
     $base+=((ord($bin[2])>>(7-$k))%2)*pow(0.5,$k+8);
    }
    for($k=0;$k<8;$k++) {
     $base+=((ord($bin[3])>>(7-$k))%2)*pow(0.5,$k+16);
    }
   
    $float=(float)$sign*pow(2,$exponent)*$base;
    return $float;
}
kjohnson at zootweb dot com
02-Jun-2008 10:23
PHP switches from the standard decimal notation to exponential notation for certain "special" floats. You can see a partial list of such "special" values with this:

<?php
for( $tmp = 0, $i = 0; $i < 100; $i++ ) {
   
$tmp += 100000;
    echo
round($tmp),"\n";
}
?>

So, if you add two floats, end up with a "special" value, e.g. 1.2E+6, then put that value unmodified into an update query to store the value in a decimal column, say, you will likely get a failed transaction, since the database will see "1.2E+6" as varchar data, not decimal. Likewise, you will likely get an XSD validation error if you put the value into xml.

I have to be honest: this is one of the strangest things I have seen in any language in over 20 years of coding, and it is a colossal pain to work around.
m dot lebkowski+php at gmail dot com
27-Feb-2008 11:18
Just another note about the locales. Consider the following code:

<?php
   
// in polish locale decimal separator is ","
   
setlocale(LC_ALL, "pl_PL");
   
$a = 5/2;
    echo (float)(string)
$a;
   
/// prints "2", so the decimal part is dropped
?>

This causes very serious problems in my opinion. In some locale combination the typecasting can be destructive.
Maybe when locale decimal separator is ",", then (float)"2,5" should be recognized as "two and a half"?
Anyway - bare that in mind and be very careful when casting floats to strings and back.
helly at php dot net
22-Oct-2007 10:10
Floating point values have a limited precision. Hence a value might not have the same string representation after any processing. That also includes writing a floating point value in your script and directly printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE 754 is read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html
sinuhet
14-Nov-2006 06:04
<?php
        define
('EPSILON', 1.0e-8);

        function
real_cmp($r1, $r2)
        {
               
$diff = $r1 - $r2;

                if(
abs($diff) < EPSILON )
                        return
0;
                else
                        return
$diff < 0 ? -1 : 1;
        }

        function
real_lt($r1, $r2)
        {
                return
real_cmp($r1, $r2) < 0;
        }

        echo
"raw compare\n";

       
$n = 0;
        for(
$i = 0.1; $i < 1.0; $i += 0.1) {
               
$n++;
                echo
"$i\t$n\n";
        }

        echo
"\nepsilon compare\n";

       
$n = 0;
        for(
$i = 0.1; real_lt($i, 1.0); $i += 0.1) {
               
$n++;
                echo
"$i\t$n\n";
        }

/*
        Outputs:

        raw compare
        0.1     1
        0.2     2
        0.3     3
        0.4     4
        0.5     5
        0.6     6
        0.7     7
        0.8     8
        0.9     9
        1       10

        epsilon compare
        0.1     1
        0.2     2
        0.3     3
        0.4     4
        0.5     5
        0.6     6
        0.7     7
        0.8     8
        0.9     9
*/
?>

So moral of this program? "Never compare floating point numbers for equality" solves only half of the problem. As seen above, even raw comparing of floats for less than (or grater than) is dangerous and epsilon (round, etc.) must be used.
TAS
28-Jul-2006 02:02
An update regarding the james dot cridland at virginradio dot co dot uk note below, I recently tried his formula using PHP 5 and it is necessary to specify the integer precision when using the round function, otherwise the output will be 0.

<? echo round((69.1-floor(69.1))); ?> // prints 0
<? echo round((69.1-floor(69.1)), 1); ?> // prints 0.1

Also, it appears that "small numbers" include everything up to 64.0.  So that

<? echo (63.1-floor(63.1)); ?>

will print 0.1 and

<? echo (64.0-floor(64.0)); ?>

will print 0, but

<? echo round(64.1-floor(64.1)); ?>

will print 0.099999999999994.
david at davidmosesNO dot SPAM dot ca
25-Mar-2006 11:48
Re: rick at ninjafoo dot com

There is no need to “always” use the BCMath functions. We just need to heed the documentation and “never compare floating point numbers for equality”.

The reason (19.6*100) !== (double)1960, is because inside a computer they are not equal.

Try this:

<?php

printf
("%.15f", (19.6*100));

?>

Outputs: 1960.000000000000227 (not 1960 as somewhat expected)

If comparison is required a few options come to mind (other than BCMath):

1) Round numbers before comparison:

<?php

$sig_figs
= 5;
echo (
round((19.6*100), $sig_figs) !== round((double)1960, $sig_figs)) ? 'not equal' : 'equal';

?>

Outputs: equal

2) Another method is to use a tolerance value, and consider numbers equal if their difference is less than the tolerance.
Luzian
17-Nov-2005 10:03
Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this:

$x = 0.23;
$js = "var foo = doBar($x);";
print $js;

This would result in a different result for users with some locales. On most systems, this would print:

var foo = doBar(0.23);

but when for example a user from Germany arrives, it would be different:

var foo = doBar(0,23);

which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!
TRI0N
24-Sep-2005 05:01
Here is a simple formula to break down a number and get rid of the decimal values.  I built this to take a number in seconds and convert it to a readable value for Server Uptimes.

<?php
$day
= floor(($uptime / 86400)*1.0) ;
$calc1 = $day * 86400 ;
$calc2 = $uptime - $calc1 ;
$hour = floor(($calc2 / 3600)*1.0) ;
if (
$hour < 10) {
$hour = "0".$hour ;
}
$calc3 = $hour * 3600 ;
$calc4 = $calc2 - $calc3 ;
$min = floor(($calc4 / 60)*1.0) ;
if (
$min < 10) {
$min = "0".$min ;
}
$calc5 = $min * 60 ;
$sec = floor(($calc4 - $calc5)*1.0) ;
if (
$min < 10) {
$sec = "0".$sec ;
}
$uptime2 = $day." Days, ".$hour.":".$min.":".$sec ;
?>

Place this where you want the results to be seen:
<?php echo $uptime2 ; ?>

For a Value of 1455587 seconds the results will show as followed:
16 Days, 20:19:47

Enjoy
rick at ninjafoo dot com
06-Jul-2005 11:04
Concider the following:

(19.6*100) != 1960 

echo gettype(19.6*100) returns 'double', However even .....

(19.6*100) !== (double)1960

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

(string)(19.6*100) == 1960

Rule of thumb, if it has a decimal point, use the BCMath functions.
feline at NOSPAM dot penguin dot servehttp dot com
13-Aug-2004 04:36
General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later.
gallico_ at hotmail dot com
07-Sep-2003 06:34
To complete the thread about testing two floating point numbers for equality, here's the way it works for *every* programming language:

<?php
// 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 05: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
15-Apr-2003 09: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 01: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
26-Mar-2003 08: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 04: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
05-Mar-2003 11: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) 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)) 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?
www.sarioz.com
05-Feb-2003 08: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.
27-Sep-2002 09:45
much easier:
  
  e.g. round(3.1415927,2) => 3.14
        round(1092,-2) => 1100
jeroen at php dot net
24-May-2001 05: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.

Les chaînes de caractères> <Les entiers
Last updated: Fri, 10 Oct 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites