开发者

Insert comma before last three digits of a mysql_fetch_array result?

开发者 https://www.devze.com 2023-04-06 13:05 出处:网络
is开发者_开发知识库 it at all possible to do this? for instance if i had $row[\'price\'] and the value of this was 15000

is开发者_开发知识库 it at all possible to do this? for instance if i had

$row['price']

and the value of this was 15000 I would like it to show as 15,000 but I dont have a clue about how to go about this? thanks for any help.


So, you want to FORMAT your data? How about using the FORMAT function?

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

EDIT: Sample query

As opposed to the SELECT * people use (too often), slightly modify your queries.

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


Try this:

$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

The 0 is the start position of the string. The -15 is the negative end position of the string.

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


If you'd like to do the formatting in MySQL then you can use the FORMAT() function: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format


From PHP, you can use number_format:

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

This will add a comma between every group of thousands. If you also want to format your price with a dot and two decimal places, use this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号