The best way is to use decimal field for money.
But if you have to use integer field:
- before saving value into db multiply it on 100.
- after loading value from db divide it on 100.
I'm trying to save amount of money in the database as integer, but when I want to display it, it gets rounded, How can I maintain integrity of amount of money.
ie. 28.8808 rounded to 29
Check out Accessors and Mutators https://laravel.com/docs/5.2/eloquent-mutators#accessors-and-mutators
For retrieving the value;
Set the column to Integer and add to the model;
public function getPriceAsCurrencyAttribute(){
if(isset($this->attributes['price']))
{
return money_format('%i', $this->attributes['price']/100);
}
return False;
}
Use in view etc, $item->priceAsCurrency
See money_format http://php.net/manual/en/function.money-format.php
I used /100 because I only need to support two decimal places. If you need to support more then change as appropriate
to save a new price
Add to model
public function setPriceFromCurrencyAttribute($value) {
$this->attributes['price'] = $value*100;
}
saving price;
$item->priceFromCurrency = '14.99';
Please or to participate in this conversation.