Reputation: 380
I want a regex which will convert using preg_replace
=> -1121234.56 to (1,121,234.56)
=> -1121 to (1,121.00)
=> 1121 to 1,121.00
Right Now I have used
$number = -12121234.56;
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
O/P -12,121,234.56
I want the above features as well.
Upvotes: 3
Views: 2710
Reputation: 2019
I could solve with preg_replace
, and number_format
$replace = preg_replace(
'/(-)([\d\.\,]+)/ui',
'($2)',
number_format($number,2,'.',',')
);
Some tests:
$number $replace
12121234.56 12,121,234.56
-12121234.56 (12,121,234.56)
-1234567.89 (1,234,567.89)
I hope this help you out.
Upvotes: 3
Reputation: 173542
You can just use number_format()
:
function myformat($nr)
{
$nr = number_format($nr, 2);
return $nr[0] == '-' ? "(" . substr($nr, 1) . ")" : $nr;
}
myformat(-1121234.56);
myformat(-1121);
myformat(1121);
See also: number_format()
Upvotes: 4