Beware of round() function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Beware: round() apparently has changed its behavior from PHP 4. For 
certain special numbers that seem to be multiples of 100,000, the return 
value is in exponential format, rather than the usual decimal format. Some 
of these special values are 1200000, 1400000, 2300000, which are returned 
as 1.2E+6, 1.4E+6, etc. You can generate your own list of these special 
numbers using this code:

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

The exponential format is fine as long as the number is only used 
internally to PHP. However, we have found two cases so far where the 
exponential format has caused errors resulting in failed transactions. 

One, if you interpolate a value in exponential format into xml, as in this 
example, then you will likely end up with an xsd validation error and a 
failed transaction:

'<AnnualIncome>' . round($income) . '</AnnualIncome>'

Two, if you have field validation code like below, this will falsely 
indicate an error when the consumer enters one of the "special" values for 
income, e.g., 1200000, which is returned as "1.2E+6":

if(!ereg("^[0-9]{1,10}$", round($_POST['income']))) {
  $errors .= "<li>Income should be whole dollars only (10 digits 
max).</li>";
}

Needless to say, not a good user experience. 

I reported this as a bug to the PHP dev team, but it was rejected. 
Regardless of what it is, it will bite you if you're not careful.

http://bugs.php.net/?id=44223&edit=2

- Kirk



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux