Reputation: 6215
I have an App in CakePHP 2.2 & MySQL. I noticed that the type casting of the value returned is string for many types like Float, Decimal, Int, Varchar, Text etc..:
Float or Decimal:
var_dump($this->field('field_name'));
string(4) "1.00"
Int
var_dump($this->field('field_name'));
string(1) "1"
This problem Not occur only using TINYINT(1) for boolean fields:
Tinyint(1)
var_dump($this->field('field_name'));
bool(true)
Normally for currency fields I set the field type as FLOAT or DECIMAL(11,2)... maybe Im wrong using this types in CakePHP? This behavior is very tedious especially with decimal fields because when the value is 0 is returned as string "0.00" that is true. So I have to always remember to force the type like this:
if((float)$this->field('price')){
....
}
Why CakePHP does not return values with the proper typecasting? How do I fix this? Thank you!
Upvotes: 1
Views: 3275
Reputation: 4856
This is NOT a CakePHP issue. This is due to the loose-typing currently used in the PHP scripting langiage. TinyInt and Boolean work since it is converted to the bool type.
The work around used by all has been to strictly cast the variable you wish to be float to float, as in your example. To check if a string is numeric you can use the is_numeric()
function:
if (is_numeric($testedFloatString)) {
//If $testedFloatString is a string representing a number cast it to float
$testedFloatString = (float) $testedFloatString;
}
This is the concept of "Type Juggling". What you need to remember for floating point numbers here is that:
$varName = (float) $varName;
$varName = (double) $varName;
$varName = (real) $varName;
will all be casted to PHP's Float. This issue will cease to exist with the long-awaited PHP 6 strict typing but we'll have to wait a bit more for that. As for now - the only way is to handle these variables yourself.
To automatically manage this in CakePHP for the Models that you need use the Model::afterFind()
callback. This callback is used "to modify results that have been returned from a find operation or to perform any other post-find logic. Also watch out for the second parameter, as when a Model's find()
is called from an associated Model the resulting array's structure will be different.
Upvotes: 2