money_format () expects parameter 2 to be double, string given

1

In the following expression in which I want to format some values:

@foreach($price_list as $price)
    $number = ($price->price_normal); 
    setlocale(LC_MONETARY, 'en_ES'); 
    echo money_format('%i', $number) . "\n";
@endfoerach

Result:

  

money_format () expects parameter 2 to be double, string given.

What am I doing wrong?

Can this be done directly in the Laravel driver and bring it to view already formatted?

    
asked by Cesar Augusto 30.07.2017 в 02:30
source

2 answers

0

To format fields of a model in Laravel , use Accessors and mutators , that is, the typical (get and set) , so if you want to format type Moneda the function you are using would be correct but you should keep in mind that this function is not available in some Operating Systems.

Instead, you could use number_format to give the result you want.

For this in your model I would define the getter , for this example I will use only two fields name and price

protected $fillable = [
    'nombre','precio'
];

/* después del get debe ir el nombre del campo seguido de Attribute*/
public function getPrecioAttribute($value) {
    return '$'.number_format($value, 2, ',', '');
}

Having this defined every time you want to obtain the attribute of the class will apply the respective format, from the view you would access normally.

@foreach ($productos as $element)
     <li><p>{{  $element->precio }}</p></li>
@endforeach

PD: There may be better ways to present the data in the view

    
answered by 30.07.2017 / 04:29
source
0

You have two options to make sure that the content is numeric:

// Convertir usando la función floatval
$number = floatval($price->price_normal);

// Convertir de forma automática (cast)
(float) $number = $price->price_normal;

It can also be assumed that the number is already formatted, including thousand separator (,) and must be deleted with str_replace.

    
answered by 30.07.2017 в 02:40