Garg - 1 year ago 91

PHP Question

I'm pulling one number from the api. The output when I call the value directly is

`1597188700000000`

Desired output on the page is

`15, 971, 887`

What I'm trying is

`function formatMoney($number, $fractional=false) {`

if ($fractional) {

$number = sprintf('%.2f', $number);

}

while (true) {

$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);

if ($replaced != $number) {

$number = $replaced;

} else {

break;

}

}

return $number;

}

Then

`formatMoney($totala)`

`1,597,188,700,000,000`

Any help is appreciated

Answer Source

The following will format your number, separating the thousands with a `,`

and stripping all zeros from the right part of the number.

```
$formattedNumber = number_format(rtrim($number, '0'), 0, ',', '.');
```