明确使用 php 将逗号添加到 sql 值

Adding commas to sql values using php explicitly

我的html看起来像这样

<h2>$<?php echo $final; ?></h2>

页面将动态吐出来自 sql table 的值。该值在 table.

中设置为整数

输出看起来像这样

46000 美元

如何让逗号自动插入看起来像:

46,000 美元

我想使用 PHP 完成此操作。

回应可以在 sql 中完成的评论。

MySQL

使用FORMAT.

对于整数:

SELECT FORMAT(Field, 0);

第二个标志是你想要的小数点后多少个数字。

对于带 2 个小数点的浮点数

SELECT FORMAT(Field, 2);

PHP

这可以使用 number_format

来完成

来自http://php.net/

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

为了增强这一点,number_format 倾向于进行一些舍入。所以如果你有花车,你可能想要更好的东西(但也许你没有,但如果你有)::

$final = 46000.12;
echo number_format( floor( $final*100 ) / 100, 2 );

Dagon makes a good point that you could also look into money_format

来自http://php.net/

$number = 1234.56;
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

使用number_format.
要将 46000 输出为 46,000,您需要:

echo number_format(46000);
//46,000