Re: Beware of round() function
| From: | Jim Lucas | Date: | Thu, 10 Apr 2008 05:48:57 +0000 |
| Subject: | Re: Beware of round() function | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-272815@lists.php.net to get a copy of this message | ||
Kirk.Johnson@zootweb.com wrote:
For the above test, is there any reason you couldn't use is_numeric() Looks like it would work in this case. <?php if ( ! is_numeric($_POST['income']) ) {On Mon, 24 Mar 2008 13:10:17 -0600, Kirk.Johnson@zootweb.com wrote:returnBeware: round() apparently has changed its behavior from PHP 4. For certain special numbers that seem to be multiples of 100,000, thereturnedvalue is in exponential format, rather than the usual decimal format.Someof these special values are 1200000, 1400000, 2300000, which arespecialas 1.2E+6, 1.4E+6, etc. You can generate your own list of theseI now have a list of 3 ways this change in behavior can bite you and result in a failed transaction. In the examples below, assume that the value passed to round() is '1200000', so that the value returned from round() is '1.2E+6'. 1. When interpolating the value into xml, resulting in an xsd validation error: <? $xml = '<AnnualIncome>' . round($income) . '</AnnualIncome>'; ?> 2. When validating user input, resulting in a false positive: <? if(!ereg("^[0-9]{1,10}$", round($_POST['income']))) { $errors .= "<li>Income should be whole dollars only (10 digits max).</li>"; } ?>numbers using this code: <?php for( $tmp = 0, $i = 0; $i < 100; $i++ ) {$tmp += 100000; echo round($tmp),"\n";} ?>
$errors .= "<li>Income should be whole dollars only ".
"(10 digits max).</li>";
}
?>
3. When interpolating a value into a stored procedure call, resulting in a type mismatch between the value passed in and the database column data type (which is likely decimal for a monetary value):
<?
$sql = "exec update_loan_financials
@application_id='$appID',
@total_debt=" . round($totalDebt);
?>
BTW, a previous poster pointed out that this is a change in behavior of the float type, in general, not of the round() function, in particular.
If you care.
I don't. I just know I have broken code to fix and customers to apologize to.
Kirk