I am working on a payment gateway and the amount parameter needs to formatted this way:amount – (digits only) the integer value of the transaction in lowest common denomination (ex. $5.20 is 520)
I have already removed the $
and all values will be rounded to 2 decimal places.
In PHP if i try to cast amount as int
ie (int)$amount
I am going to loose the .20 in the example though its needed. What could be the best way to go about this?
You can multiply the amount by 100 and then convert it...
$amount = (int)($amount*100);
So 5.20 becomes 520.
If you are not sure about the number of decimal places, you could use regex to strip non-digital values from your string.
echo preg_replace('~\D+~', '', $amount);
\D
means any non-numeric character. +
means one or more.
If the value needs to be cast as an integer (rather than a string) write(int)
just before preg_replace
.
Of course, you could use str_replace()
and target known characters like: $
and .
(and -
if it may exist).
After some feedback from the OP...
You can round and format in one step with number_format()
.
Code: ( Demo: https://3v4l.org/ir54s )
$amounts = array(0.001, 0.005, 5.20, 5.195, 5.204, 5);
foreach ($amounts as $amount) {
echo $amount , "->" , (int)number_format($amount, 2, '', '')."
";
}
Output:
0.001->0
0.005->1
5.2->520
5.195->520
5.204->520
5->500