PHP:通过插入逗号来格式化数字字符串
问题描述:
I need a way to convert a number into formatted way by inserting comma at suitable places. Can it be done using regex?
Example:
12345 => 12,345
1234567 =>1,234,567
我需要一种方法,通过在适当的位置插入逗号将数字转换为格式化方式。 是否可以使用正则表达式完成? p>
示例: p>
12345 => 12,345
1234567 => 1,234,567
code> pre>
div>
答
There is no need go for regex , you can easily do it using the number_format() function.
echo number_format(12345); // prints 12,345
echo number_format(1234567); // prints 1,234,567
.
$arr = array(
1234567890,
123456789,
12345678,
1234567,
123456,
12345,
1234,
123,
);
foreach($arr as $num) {
echo number_format($num)."
";
}
Output:
1,234,567,890
123,456,789
12,345,678
1,234,567
123,456
12,345
1,234
123
答
For Integer value
$intVal=2151;
echo number_format((string)$intVal); // output -> 2,151