How to insert float variable in database properly

浪尽此生 提交于 2019-12-13 21:08:37

问题


I have the following table

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;

and I'm trying to insert a line in it using 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, '.', ',').' )';

The problem is that "orderAmount" is inserted without the decimal part. For example if $form_order_amount=30,45 then 30 is what's inserted in database.

I used number_format() because it's supposed to convert "30,45" to "30.45".


回答1:


Convert form_order_amount to float first, using this:

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



回答2:


I had a similar problem. This is how I did it. Source php manuals

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)))
    );
}


来源:https://stackoverflow.com/questions/26137364/how-to-insert-float-variable-in-database-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!