Home > Mobile >  reversing the value of number after converting using str_pad
reversing the value of number after converting using str_pad

Time:12-16

I am converting the numbers to be used in API

for example:

 $total = 100.5;
 $purchaseAmt = str_pad($total, 13, "0", STR_PAD_LEFT);
 $formattedPurchaseAmt = str_pad(''.($purchaseAmt*100), 12, "0", STR_PAD_LEFT);

it will output 000000010050

Now, how I can do the opposite, if I have 000000010050 i want to get 100.5

Thanks

CodePudding user response:

I think if you round up your float and format it to always have two numbers after the decimal, you could simply do the opposite of what you do, which is divide by 100

$total = round(100.5, 2);
 $purchaseAmt = str_pad($total, 13, "0", STR_PAD_LEFT);
 $formattedPurchaseAmt = str_pad(''.($purchaseAmt*100), 12, "0", STR_PAD_LEFT);

#reverting the process
$newTotal = (int)formattedPurchaseAmt / 100; //output: 100.5

CodePudding user response:

Test this code:

echo number_format($formattedPurchaseAmt/100, 1, '.');

Maybe it does not suits all cases, so test it well before to use in production.

  •  Tags:  
  • php
  • Related