PHP 最小通用面额

PHP lowest common denomination

我正在开发一个支付网关,金额参数需要这样格式化:
amount – (digits only) the integer value of the transaction in lowest common denomination (ex. .20 is 520)
我已经删除了 $,所有值都将四舍五入到小数点后两位。

在 PHP 中,如果我尝试将 amount 转换为 int(int)$amount 我将放弃示例中的 .20虽然它需要。解决此问题的最佳方法是什么?

您可以将金额乘以 100,然后进行换算...

$amount = (int)($amount*100);

所以 5.20 变成 520。

如果您不确定小数位数,您可以使用正则表达式从字符串中去除非数字值。

echo preg_replace('~\D+~', '', $amount);

\D 表示任何非数字字符。 +表示一个或多个。

如果需要将值转换为整数(而不是字符串),请在 preg_replace 之前写入 (int)

当然,您可以使用 str_replace() 并定位已知字符,例如:$.(如果存在 -)。


在 OP 的一些反馈之后...

您可以使用 number_format() 一步进行舍入和格式化。

代码:(演示: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, '', '')."\n";
}

输出:

0.001->0
0.005->1
5.2->520
5.195->520
5.204->520
5->500