note 83143 deleted from function.number-format by danbrown
| From: | danbrown@php.net | Date: | Mon, 20 Jun 2011 15:18:55 +0000 |
| Subject: | note 83143 deleted from function.number-format by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180733@lists.php.net to get a copy of this message | ||
Note Submitter: Vladimir Kornea
----
In response to gabrielu at gmail dot com concerning number_format(14.95 * 0.3, 2) returning 4.48
rather than 4.49:
What you're seeing is not specific to the number_format() function, but is an intractable
consequence of performing floating-point arithmetic. Your computer is unable to create exact
representations of certain floating-point numbers and instead approximates. The result of your
calculations is stored internally not as 4.485 but as something resembling 4.484999... This is the
reason for the advice to never check for equality when dealing with floating-point numbers--while
PHP might echo the same thing, the internal representation could be quite different. See the code
below.
<?php
$array = array();
$array['assigned'] = 4.485;
$array['calculated'] = 14.95 * 0.3; // equals 4.485 in reality
echo "Sorting ascending\n"; // notice that 'calculated' gets sorted ahead of
'assigned'
asort($array);
foreach($array as $key => $value) {
echo "$key: $value becomes " . number_format($value, 2) . "\n";
}
echo "Sorting descending\n";
arsort($array); // notice that 'assigned' gets sorted ahead of 'calculated'
foreach($array as $key => $value) {
echo "$key: $value becomes " . number_format($value, 2) . "\n";
}
?>
Output:
Sorting ascending
calculated: 4.485 becomes 4.48
assigned: 4.485 becomes 4.49
Sorting descending
assigned: 4.485 becomes 4.49
calculated: 4.485 becomes 4.48