PHP 比较浮点值

PHP Comparing float values

我在比较两个 PHP 值时遇到问题。第一个值作为查询字符串中的参数传递,而第二个参数是 sql 查询的结果。

这里我需要的逻辑是比较两个值,这样如果用户有足够的信用,他的付款就可以被处理,否则,会显示一个错误信息。

这是我的代码:

public function storeNewTicket($userId, $amount, $validity) {

        $currentBalance = $this->getBalance($userId);
        $floatCurrentBalance = floatval($currentBalance);
        $floatAmount = floatval($amount);


        if ($floatCurrentBalance > $floatAmount) {

            /*Proceed with the insert*/
        }
        else {
            echo "You don't have enough credit to process this payment."
        }
    }

在同一文件中名为 getBalance() 的单独函数中,我从另一个 table 获取用户的当前余额并将其作为对象返回。我 100% 确定这是有效的。这是代码:

public function getBalance($userId) {

    $stmt = $this->conn->prepare("SELECT balance FROM userbank WHERE UserId = ?");    
    $stmt->bind_param("s", $userId);

    if ($stmt->execute()) {
        $bal = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $bal['balance'];
    } else {
        return NULL;
    }
}

代码总是通过 else 子句并回显:You don't have enough credit to process this payment.

有人可以帮我了解如何将变量转换为小数或浮点数并进行比较吗?

使用浮点数时请使用BC Math函数。 要比较浮点数,请使用 bccomp.

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

注意第三个参数是小数点后的位数

我找到了问题所在。 My getBalance() 方法在转换为浮点数时实际上返回值 1。 1 是记录在数组中的位置。将 $floatCurrentBalance 的声明更改为:$floatCurrentBalance = floatval($currentBalance['balance']);