带小数的Mysql问题

时间:2010-03-25 17:53:31

标签: mysql decimal

我有两个字段   - 金额(十进制(11,2))   - gift_amount(十进制(11,2))

当我对值等于或低于999.99的值进行更新时,它会正确保存。

但是,如果我重复一遍,那么它会将值降回到1 - 10。

这是一个已知问题还是使用小数我错了?

这是我正在做的一些PHP代码,只是为了让它更清晰(尽管我100%不是PHP的错误。

    if ($total_balance >= $cost) {

        if ($this->user->balance->gift_amount > 0) {
            $total_to_be_paid                   = number_format($cost, 2) - number_format($this->user->balance->gift_amount, 2);//figure out how much is left after the gift total
            $this->user->balance->gift_amount   -= number_format($cost, 2); //deduct from the gift balance
            $this->user->balance->gift_amount   = (number_format($this->user->balance->gift_amount, 2) < 0) ? number_format(00.00, 2) : number_format($this->user->balance->gift_amount, 2); //if the gift balance went below 0, lets set it to 0

            if ($total_to_be_paid > 0) {
                $this->user->balance->amount = number_format($this->user->balance->amount, 2) - number_format($total_to_be_paid, 2);
            }

        } else {
            $this->user->balance->amount = number_format($this->user->balance->amount, 2) - number_format($cost, 2);
        }

        if ($object = Model_ClipBought::create(array('clip_id' => $clip->id, 'user_id' => $this->user->id, 'currency_name' => $user_currency, 'cost' => $cost, 'downloads' => $clip->downloads, 'expires' => time() + ($clip->expires * 86400)))) {
            $this->user->balance->save();
            $download = new Model_Download(ROOT_PATH."/public/files/Clip/$clip->file_url");
            $download->execute();
        } else {
            throw new exception('We could not finish the purchase, this has been reported, sorry for the inconvenience.');
        }
    } else {
        throw new exception('You dont have enough money in your account todo this');
    }

    exit;
}

1 个答案:

答案 0 :(得分:1)

在实际输出/向用户显示号码之前,您不应该使用number_format。它会插入系统的默认千位分隔符(默认情况下为逗号):

number_format(999.99, 2) -> 999.99
number_format(1234.56, 2) -> 1,234.56

如果您在PHP的后续计算中使用这些值,或者尝试逐字插入MySQL,您将获得时髦的价值:

 2345.67 + 1.0 = 2346.67

但是使用number_format()会给出这个解析序列:

 number_format(2345.67) + 1.0 -> "2,345.67" + 1.0
 "2,345.67" + 1.0 ->   "2" + 1.0
 2 + 1.0 -> 3

注意“2,345.67”如何被截断为“2” - 逗号将你的好数字变成一个字符串,现在你受到字符串 - >整数解析规则的约束,它会在第一个之后删除所有内容字符串中的数字字符。

如果您在整个计算过程中尝试将所有内容保持在小数点后2位,请考虑使用sprintf('%0.2f', $value)代替。