首页 > 解决方案 > 我如何将小数限制为两位

问题描述

大家好,我希望你能帮助我。

我有'value' => $amount_to_pay并且我希望我的 $amount_to_pay 乘以 0.11,但输出仅限于小数点后 2 位。它适用于贝宝。

我使用过'value' => $amount_to_pay*0.11,但小数点后的内容很长,并且从 PayPal exp: 589.24*0.11 = 64.8164 返回错误我希望输出为 64.81

谢谢

标签: phppaypaldecimalcalculation

解决方案


您可以使用round()N 小数四舍五入

'value' => round($amount_to_pay * 0.11, 2) // 64.82

正如@PrestonPHX 提到的那样,它给出了一个整数值。如果你想“截断小数,你可以使用:

'value' => (int)($amount_to_pay * 100) / 100 // 64.81

要使用动态小数位数,您可以使用:

$nb = 2; // number of decimals
$exp = pow(10, $nb);
echo (int)($amount_to_pay * $exp) / $exp;

推荐阅读