这种数字格式有什么问题?

What's wrong with this number format?

我想回显 MySQL 列中的值,但我想得到千位的逗号。因此,我收到的不是“5,000”,而是 5000。我使用的是 number_format,但这似乎有问题,因为浏览器控制台显示的是“0,00”,而不是我通过 Jquery/Ajax 调用的值.一些想法?我将数字作为字符串插入。示例:("INSERT INTO Votes (votes) VALUES ('10000')"; 也许它有什么关系?

这是我的 php 代码,用于从 MySQL:

获取数据
$co = $_REQUEST['color'];

$sql = "SELECT SUM(votes) AS sum FROM Votes WHERE color = '$co'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo number_format($row["sum"], 2, ",", ".");
}
else {
echo "No result found";
}

只需执行 number_format("5000"),您将得到 5,000 作为结果。

根据您的示例推断,它将是:

number_format($row['sum'])

例如,如果 $row['sum'] 是 5000,您将得到 5,000 作为输出。

好吧,在 PHP 中,你已经在做的是正确的方法,我不确定你为什么会得到错误的输出。

但是,您也可以尝试直接从 MySQL:

格式化数字
$sql = "SELECT FORMAT(SUM(votes), 2) AS sum FROM Votes WHERE color = '$co'";

这样做,$row["sum"]应该直接格式化了。

如果这仍然不起作用,那么您很可能在客户端有问题。

使用 number_format($row["sum"],2,'.','');