【问题标题】:How to insert float variable in database properly如何在数据库中正确插入浮点变量
【发布时间】:2014-11-26 01:22:44
【问题描述】:

我有下表

CREATE TABLE IF NOT EXISTS `payment_data` (
  `orderid` int(11) NOT NULL,
  `orderDesc` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `orderAmount` float NOT NULL,
  UNIQUE KEY `orderid` (`orderid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我正在尝试使用 PHP 在其中插入一行。

$sql = 'INSERT INTO payment_data '.
           '(orderid, orderDesc, name, email, orderAmount) '.
           'VALUES ( '.$form_order_id.', "'.$form_order_desc.'", "'.$form_name.'", "'.$form_email.'", '.number_format($form_order_amount, 2, '.', ',').' )';

问题是“orderAmount”插入时没有小数部分。例如,如果 $form_order_amount=30,45 那么 30 就是插入到数据库中的内容。

我使用 number_format() 是因为它应该将“30,45”转换为“30.45”。

【问题讨论】:

  • 你需要 float orderAmount float(7,2)` 或其他需要的小数精度
  • 30,45 小数点为, 对计算机来说不是有效数字;插入 MySQL 时需要小数点 (.)
  • 也就是说,不要将float 用于数据库资金,使用decimal.... 甚至更好,将值调整为美分,以便在需要时使用整数对浮点精度可能导致问题的税收计算等进行调整
  • number_format() 应该在显示浮点值时使用,而不是在内部存储时使用,它不会将30,45 转换为30.45,但会反过来

标签: php mysql sql number-formatting


【解决方案1】:

首先将 form_order_amount 转换为浮点数,使用以下方法:

$form_order_amount = floatval(str_replace(',', '.', $form_order_amount));

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。我就是这样做的。源码phpmanuals

    public static function tofloat($num) {
        $dotPos = strrpos($num, '.');
        $commaPos = strrpos($num, ',');
        $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
                ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    
        if (!$sep) {
            return floatval(preg_replace("/[^0-9]/", "", $num));
        }
    
        return floatval(
            preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
            preg_replace("/[^0-9]/", "", substr($num, $sep + 1, 
            strlen($num)))
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多