0

I'm developing a browser extension (content script) that scans and highlights certain words on a page, and uses AJAX and PHP to echo back content into a tooltip that appears when a user hover over said words. The PHP file uses an API to retrieve an XML file which it then parses and echoes back.

One thing that gets echoed into the tooltip is a money value (the 'total' attribute in the code below). As of now, it spits back values like "$612343", $121100", "$1222" etc. What I want is for the money to be formatted properly with commas like "$6,123,234" instead of "$6123234". How would I do this?

Here is the PHP code:

echo "<table><tr id='thasdfdfd'><th id='thasdfdfd'>Contributors</th><th>Total</th></tr>";
foreach ($data['response']['industries']['industry'] as $ind) {
    foreach ($ind as $row) {
        echo "<tr><td>" . $row['industry_name'] . " " . "</td><td>" . "$" . 
            $row['total'] . '</td></tr>';
    }
}
Nicholas Rubin
  • 317
  • 1
  • 4
  • 14

2 Answers2

3

You probably want something like number_format. It lets you specify the thousands separator, decimal places, and decimal separator. Just the normal, single argument usage will probably yield what you want.

<?php
echo number_format('612343'), PHP_EOL;
// output: 612,343
chrisguitarguy
  • 2,329
  • 20
  • 18
2

You might also consider formatting depending on Locale. For this use NumberFormatter class instead of number_format mentioned by Chris.

Tomasz Kapłoński
  • 1,320
  • 4
  • 24
  • 49