/**
* Reverse the digits of a number (or numeric string)
* and insert a comma every 3 characters.
*
* 123456789 → 987,654,321
* -1200300 → -003,002,1
*
* Works with:
* • integers
* • numeric strings
* • negative values
* • decimal parts (keeps them, but does not re-group)
*/
function reverseWithThousandsComma($number)
{
// 1) Remember the sign and strip it temporarily
$isNegative = false;
if (strpos($number, '-') === 0) {
$isNegative = true;
$number = substr($number, 1);
}
// 2) Separate decimal part, if any
[$intPart, $decPart] = array_pad(explode('.', (string)$number, 2), 2, '');
// 3) Reverse the integer part and chunk it 3-by-3
$reversed = strrev($intPart);
$chunked = implode(',', str_split($reversed, 3));
// 4) Glue everything back together
$out = $chunked;
if ($decPart !== '') {
$out .= '.' . strrev($decPart); // keep decimal digits, but reversed as well
}
if ($isNegative) {
$out = '-' . $out;
}
return $out;
}