How to convert decimal/double values from form to database

Hi,

What is the best method to convert the decimal/double values to database?

Example:

Form field: 1.200,50 To: 1200.50

I know that we can use replace and other functions, but i want know an automatic method from Yii because i need transform some values to can use to male calcs and store on database.

Model::beforeSave()

Model::afterFind()

Man, is not this that i want.

I want the method to convert the value, not the place to convert.

I know that i have to put on this model methods.

What i need is a Yii native method to convert my values from form(1.200,50) to PHP float format (1200.50).

I can do with php using replace, but if exist a native method from Yii will be better, and if is integrated with locale, better again.

A poor solution is:


$value = '1.200,50';

$value = str_replace('.', '', $value);

$value = str_replace(',', '.', $value);

$value = (float)$value;

But imagine make it with more than 10 form fields to make calcs with it.

Maybe CFilterValidator and using your custom function that wraps your str_replace calls? BTW i think strtr() is faster if you’re only replacing single characters.

But to format a number to our locale we can use the "numberFormater", so dont have a "numberFormater" to format the number to PHP format or database format?

Hi,

The afterFind function is obvious, you just pass the pattern you want to the format function of CNumberFormatter and you get the localized version of your pattern.

The beforeSave function was harder. I decided to first check if there even was a number to convert then compare the decimal symbols of the current locale and the source locale and if they are different then do a PHP strtr to replace the current locale group and decimal symbols with the source group and decimal symbols before saving.

Here is the code I added to the model:




public function beforeSave() {

    if($this->myNumber)

    {

        if(($currentDecimal = Yii::app()->getLocale()->getNumberSymbol('decimal')) != ($sourceDecimal = Yii::app()->getLocale(Yii::app()->sourceLanguage)->getNumberSymbol('decimal')))

        {

            $currentGroup = Yii::app()->getLocale()->getNumberSymbol('group');

            $sourceGroup = Yii::app()->getLocale(Yii::app()->sourceLanguage)->getNumberSymbol('group');

            $this->myNumber = strtr($this->myNumber, $currentDecimal.$currentGroup, $sourceDecimal.$sourceGroup);

        }

    }

    return parent::beforeSave();

}






public function afterFind() {

    if($this->myNumber)

        $this->myNumber = Yii::app()->numberFormatter->format('#,##0.00', $this->myNumber);

    return parent::afterFind();

}



Some time ago i created an extension for this: http://www.yiiframework.com/extension/decimali18nbehavior