gameover
gameover

Reputation: 12033

PHP: Format a numeric string by inserting comma

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

Upvotes: 2

Views: 954

Answers (2)

Kailas
Kailas

Reputation: 3231

For Integer value

$intVal=2151;

echo number_format((string)$intVal); // output -> 2,151

Upvotes: 0

codaddict
codaddict

Reputation: 455282

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)."\n";
}

Output:

1,234,567,890
123,456,789
12,345,678
1,234,567
123,456
12,345
1,234
123

Upvotes: 11

Related Questions