|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2006-01-14 05:15 UTC] adi at rogers dot com
Description: ------------ Very lame/unreliable ;) Both round() and number_format() succumb to this problem. They cannot handle float or double variables properly even though those variable types are "flawed / limited" as apparently described numerous times on here by PHP personnel. Well my code below appears to showcase the bug which will hopefully not be shot off as "bogus" like many times before as reported in the past by various people. I found a work-around which I will now be using. Convert your value to a string variable before passing it to the round() or number_format() function. Reproduce code: --------------- $num=12.5*1.15; // Produces 14.375 as type: double. $num_same_thing=14.375; // Produces 14.375 as type: double. echo "Wrong: ".round($num, 2)."\r\n"; echo "Wrong: ".number_format($num, 2)."\r\n"; echo "'Magically' correct: ".round($num_same_thing, 2)."\r\n"; echo "'Magically' correct: ".number_format($num_same_thing, 2)."\r\n"; // The above two variables are the same value and same type, yet are rounded differently. settype($num, "string"); // Now that $num is a string, we get the right result. echo "Converted to string and is now correct: ".round($num, 2)."\r\n"; echo "Converted to string and is now correct: ".number_format($num, 2)."\r\n"; Expected result: ---------------- The functions should have outputted 14.38 no matter how the variables of type 'double' were assigned the value 14.375. PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 05:00:01 2025 UTC |
Code: for ($i = 1.075;$i <= 1.975;$i=$i+0.1) {echo round($i,2);} Result: 1.08, 1.18, 1.28, 1.38.... But if echo round(1.275,2); echo round(1.275*100); we have 1.27 and 127. Another "same" example: for ($i = 1.075;$i <= 20.975;$i=$i+0.1) {echo round($i,2);} Win2003 + Apache 2.0.59 + php 5.1.6Similar problem on Vista home premium, PHP 5.2.5: <?php $numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009); foreach ($numbers as $number) print $number."->".number_format($number, 2, '.', ',')."<br>"; ?> 0.001->0.00 0.002->0.00 0.003->0.00 0.004->0.00 0.005->0.01 0.006->0.01 0.007->0.01 0.008->0.01 0.009->0.01 as expected... however... <?php $numbers = array(78.221,78.222,78.223,78.224,78.225,78.226,78.227,78.228,78.229); foreach ($numbers as $number) print $number."->".number_format($number, 2, '.', ',')."<br>"; ?> 78.221->78.22 78.222->78.22 78.223->78.22 78.224->78.22 78.225->78.22 78.226->78.23 78.227->78.23 78.228->78.23 78.229->78.23 ? 78.225->78.22 ? no fiddling with the precision parameter enabled me to fix this.