Home > Mobile >  PHP - Convert USD to IQD closest price
PHP - Convert USD to IQD closest price

Time:11-18

I have a price number converted from USD to IQD (Iraqi Dinar) according to the exchange rate specified, for example:

// Conversion method
function USD_to_IQD($price){
   $exchangeRate = 1450;
   return round($price * $exchangeRate);
}

$price = 1 // USD
$convertedPrice = USD_to_IQD($price)

// result: 1450 IQD

That's all fine for now, I'm getting the price from USD to IQD (my country currency).

But the problem here is, the converted price is (1450) and the (450) should be close to either (250, 500, 750, 1000) according to the case returned, which is in this case will be closed to (500) then the result will be (1500) as I need.

examples:

$price = 1930 // IQD, should be 2000
$price = 1600 // IQD, should be 1750
$price = 1030 // IQD, should be 1250
...

according to the case (the converted price)!

any help?

CodePudding user response:

You can simply do this with little calculation alongwith ceil function.

I've kept 250 static as it is the multiple of all your options.

echo ceil(1930 / 250) * 250; // Output: 2000
echo ceil(1600 / 250) * 250; // Output: 1750
echo ceil(1030 / 250) * 250; // Output: 1250

CodePudding user response:

you can use this method:

// Conversion method
function USD_to_IQD($price){
   $exchangeRate = 1450;
   $step = 250;

   $calculatedPrice = $price * $exchangeRate;
   $surplus = ($calculatedPrice % $step);
   return $calculatedPrice   ($surplus ? ($step - $surplus) : 0);
}
  • Related