note 83143 added to function.number-format

From: Date: Mon, 12 May 2008 22:16:51 +0000
Subject: note 83143 added to function.number-format
Groups: php.notes 
Request: Send a blank email to php-notes+get-139316@lists.php.net to get a copy of this message
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 ---- Server IP: 64.71.164.2 Probable Submitter: 65.106.184.147 ---- Manual Page -- http://www.php.net/manual/en/function.number-format.php Edit -- https://master.php.net/note/edit/83143 Del: integrated -- https://master.php.net/note/delete/83143/integrated Del: useless -- https://master.php.net/note/delete/83143/useless Del: bad code -- https://master.php.net/note/delete/83143/bad+code Del: spam -- https://master.php.net/note/delete/83143/spam Del: non-english -- https://master.php.net/note/delete/83143/non-english Del: in docs -- https://master.php.net/note/delete/83143/in+docs Del: other reasons-- https://master.php.net/note/delete/83143 Reject -- https://master.php.net/note/reject/83143 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139316) next »