【问题标题】:PHP Comparing two values of type integer and double is giving incorrect resultsPHP比较整数和双精度类型的两个值给出不正确的结果
【发布时间】:2019-12-09 15:21:18
【问题描述】:

我正在检查 stripe webhook 发送的支付金额与我的数据库中的应付发票金额的值。

在我的数据库中,发票金额存储为 decimal(10,2)

我有 10 张发票,每张 33.60 = 336.00

//i.e.
$invoices_amount = 336.00;

Stripe 正确发送的金额为 336

{
"gateway_transaction_id":"ch_xxxxxxxxxxxxxx",
"internal_transaction_id":"22",
"transaction_amount":336,
"transaction_currency":"usd",
"transaction_status":"passed"
}

//i.e.
$transaction_amount = 336;

但是,当我执行验证逻辑以检查支付的金额是否等于发票总额时,比较结果返回 false

    if($transaction_amount >= $invoices_amount){
        //passed
    }else{
      //failed
    }

我在上述检查中失败了。

我已经使用 gettype 检查了变量类型:

gettype($transaction_amount) = integer

gettype($invoices_amount) = double

更奇怪的是,这用于验证一直都很好。

【问题讨论】:

标签: php comparison gettype


【解决方案1】:

我检查了代码,它对我来说工作正常。例如,

<?php

$invoices_amount    = 360.00;
$stripe_amount      = 360;

 if($stripe_amount >= $invoices_amount)
  {
        //passed
        echo 'passed'; 
  }
else
  {
      //failed
      echo 'failed';  
  }
?>

给了我“通过”的结果。也许您可以尝试像这样将条纹数量转换为浮动:

<?php
$invoices_amount    = 360.00;
$stripe_amount      = (float)360;
if($stripe_amount >= $invoices_amount)
{
//passed
echo 'passed'; 
}
else
{
//failed
echo 'failed';  
}
?>

希望这对你有用。

【讨论】:

    【解决方案2】:

    比较两个数字时,您可以使用 BC-MATH 扩展。

    $result = bccomp($transaction_amount, $invoices_amount, 2);
    

    $result$transaction_amount = $invoices_amount 时为0

    $result$transaction_amount &gt; $invoices_amount 时为 1

    $result$transaction_amount &lt; $invoices_amount 时为-1

    $transaction_amount 转换为浮动 (float)$transaction_amount,然后比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多