【问题标题】:Insert comma before last three digits of a mysql_fetch_array result?在 mysql_fetch_array 结果的最后三位之前插入逗号?
【发布时间】:2011-11-22 20:22:31
【问题描述】:

是否有可能做到这一点? 例如,如果我有

$row['price']

这个值是 15000 我希望它显示为 15,000,但我不知道该怎么做? 感谢您的帮助。

【问题讨论】:

  • 你的数据库中是不是没有逗号的值15000???

标签: mysql arrays fetch


【解决方案1】:

那么,您想格式化您的数据吗?使用FORMAT函数怎么样?

FORMAT(X,D)

Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. D should be a constant value.

mysql> SELECT FORMAT(12332.123456, 4);
        -> '12,332.1235'
mysql> SELECT FORMAT(12332.1,4);
        -> '12,332.1000'
mysql> SELECT FORMAT(12332.2,0);
        -> '12,332'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format

编辑:示例查询

与人们使用(太频繁)的 SELECT * 相反,稍微修改您的查询。

SELECT id, fullName, position, FORMAT(pay, 0) as pay 
FROM Employees WHERE lastName = 'Rubble';

【讨论】:

  • 老实说,我不明白我是如何为一个结果做到这一点的,因为其他结果既不是数字也不需要格式化。
  • @Bob:示例查询是否更有意义?
【解决方案2】:

试试这个:

$row['price'] = 15000;
echo substr($row['price'], 0, -3) . ',' . substr($row['price'], -3);

echo substr($row['price'], 0, -3); // == 15
echo substr($row['price'], -3); // == 000

0 是字符串的起始位置。 -15 是字符串的负结束位置。

http://at2.php.net/manual/en/function.substr.php

【讨论】:

  • 谢谢你的工作,你能给我解释一下吗?即 0 在这里做什么: substr($row['price'], 0, -3) 我可以猜到负 3 是逗号位置..
  • so 0, -3 = 0 start -3 from the end 然后第二个只有-3的只是说从最后开始的数量? (为-3)。
  • 是的,没错。看PHP手册,例子很多。
【解决方案3】:

如果您想在 MySQL 中进行格式化,那么您可以使用 FORMAT() 函数:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format

【讨论】:

    【解决方案4】:

    在 PHP 中,你可以使用number_format:

    $formatted = number_format($row['price']);
    

    这将在每组数千个之间添加一个逗号。如果您还想用一个点和两位小数来格式化您的价格,请使用:

    $formatted = number_format($row['price'], 2);
    

    【讨论】:

    • 格式化值存储在$formatted中。你试过echo $formatted; 来检查输出吗?
    • 该功能的价格是多少?是否 > 1000?另外,既然是价格,你可能也想要小数,对吧?那么你必须使用number_format($row['price'], 2) 保留小数点后两位。
    猜你喜欢
    • 2011-11-10
    • 2012-01-08
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多