插入数据库后小数四舍五入

Decimal is rounded after insert into DB

我 运行 在 MySQL 中插入带 PHP 的小数时遇到问题。 该数字被格式化为货币,存储在会话变量中。

$_SESSION['total'];

使用 number_format 将点替换为逗号给出了正确的输出:

$amount= number_format((float)$_SESSION['total'], 2, ",", '');
echo $amount;
//output = 2,85

现在我需要将变量 $amount 插入到数据库中,操作如下:

$query = "INSERT INTO testtable VALUES" . "('$amount', 'NULL')";
$result = $con->query($query);

插入时,数字插入为“2,00”而不是“2,85”。我也尝试在没有 number_format 的情况下这样做,但我得到了相同的结果。

该行设置为十进制(10,2)。

怎么可能变量 echo 是正确的,但 insert 将它四舍五入?

number_format() 的输出是一个字符串,问题是 MySQL / php 不知道逗号 , 作为小数分隔符,所以你的字符串 2,85 通过使用字符串中作为有效数字字符的第一个字符转换为数字。

在进行任何计算或数据库插入之前,您应该将字符串转换为实数,方法是将 , 替换为 . 并将其转换为浮点数:

$number = (float) str_replace(',', '.', $amount);

如果您的会话变量包含实际数字而不是字符串,您应该直接使用它们。

请注意,使用浮点数可能会导致精度问题/舍入错误。如果是这种情况,您应该只使用整数(例如,美分表示金额,所以 285 而不是 2.85)。

您需要使用点分隔符而不是逗号来插入。

$amount = number_format((float)$_SESSION['total'], 2, ".", '');
echo $amount; // prints 2.85
$query = "INSERT INTO money (total,second_field) VALUES" . "($amount, 'NULL')";
$result = $conn->query($query);

我们使用 number_format() 方便用户阅读。在声明中 $金额= number_format((float)$_SESSION['total'], 2, ",", ''); $amount 是字符串,将字符串插入到具有小数类型的 mysql 字段将插入带有警告的记录

1 row inserted. Warning: #1265 Data truncated for column 'decimal_test' at row 1

您可以使用 str_replace 删除数字中的“,”并将值插入 mysql table,如下所示

$_SESSION['total'] = "2,85";
$total_in_decimal = str_replace(',', '.', $_SESSION['total']);
$query = "INSERT INTO testtable VALUES" . "('$total_in_decimal', 'NULL')";
$result = $con->query($query);