Laravel Deal with Money in PHP Applications

Laravel Deal with Money in PHP Applications

 Laravel Deal with Money in PHP Applications

Dear Artisan's, today I'll show you how to deal with money related operations. The most problem today I see with money related problems 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 the typical behavior of Money. 


Typical behavior of Money

 So, before starting the discussion one question arises. How do you save the money in a Database? Or how do you save the defined 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 to take the whole decimal to the database so that no rounding issue will be there. Suppose it is just 107 and there is the issue of 0.0001 and what if others like Iranian Rial which is 42275. So, if we use the below 

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

and later 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 work. Thanks for reading. 🙂

Reactions

Post a Comment

0 Comments

close