Garg Garg - 1 month ago 22
PHP Question

Simple number format from api

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)
( $totala is the amount from api ) and I see on the page

1,597,188,700,000,000


Any help is appreciated

Answer

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, ',', '.');