Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace brackets and add minus sign to a number using PHP

Tags:

php

I have this variable- $number which may contain different types of number format.

Type1: $number=200,000.00 ; Type2: $number=(200,000.00) ; Type3: $number=(20.50) ;

If the number has brackets I want to remove the brackets and add a minus sign on its left side.

Example: If the number is $number=(200,000.00) ; I want to convert it to -200,000.00 or in case of $number=(20.50) ; I want to convert it to -20.50 but for $number=200,000.00 ; I want to keep it just the way it is.

I have tried this preg_replace('/[()^\d-]+/', '', $number); but its not working.

Could you please show me how to get this done?

Thanks :)

like image 429
black_belt Avatar asked Aug 29 '12 12:08

black_belt


3 Answers

You can do as follows

str_replace(array("(",")"),array("-",""),$number);
like image 95
Vamsi Avatar answered Sep 22 '22 17:09

Vamsi


I think this should do what you want:

if (strpos($number, "(") !== false && strpos($number, ")") !== false)
    $number = '-'. trim($number, "()");

Example: http://codepad.org/Yhb80H0v

like image 31
Travesty3 Avatar answered Sep 21 '22 17:09

Travesty3


Your $number has to be a string to let PHP "know" about the parentheses. Use this code:

$number = "(1,000.2)";
$number = preg_replace('/\(([0-9,.]+)\)/', '-\1', $number);
print $number;
like image 29
poplitea Avatar answered Sep 23 '22 17:09

poplitea