Laravel Deal with Money in PHP Applications

Hello Artisan's, today I'll show you how to deal with money related operations. The most problem today I see with money related problem is when the website has multi currency feature. And the main problem is not matching the floating point value after decimals.  The main thing we'll cover is typical behavior of Money. 

Typical behavior of Money

 So, before start the discussion one question is arises. How do you save the money in Database? Or how do you save the define the column for money? Like below?

$table->decimal('price', 8, 2);
// 8 is total digits, 2 is decimal digits

And then when we need to show the price we do this

number_format($product->price, 2) 

But that's a wrong process. I'll say again that it's a wrong process. You may ask why? So, let's look at the below calculation

$amount = 107.0277; //suppose 1usd = 107.0277 BDT
$quantity = 77;
$product->price = $amount * $quantity //8,241.1329
$product->save() //so in DB it'll save as 8,241.14 because we use the ($table->decimal('price', 8, 2))

So, what happens next if we want to retrieve the currency rate of BDT from product price 

$price  = $product->price; //8,241.14
$quantity = 77;
$bdt = $price/$quantity; //107.0277922077922 where our actual rate is 107.0277

So, the correct way is always take whole decimal to the database so that no rounding issue will be there. Suppose it is just 107 and there is issue of 0.0001 and what if others like Iranian Rial which is 42275. So, if we use below 

 // 8 is total digits, no bounding to decimal digits

and later if we use 

number_format($product->price, 2) 

then there will be no issue I hope

That's it for today. I hope this will help in future works. Thanks for reading. ๐Ÿ™‚