Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have a negative numbers for that i want to remove the negative sign and add braces to first and last of the numbers

for eg:

-556445.90 to (556445.90) like this.
Posted

I assume that is is to do with formatting a number for output?
ToString has an overload that accepts a format string:
C#
int neg = -16;
int pos = 16;
Console.WriteLine(neg.ToString("##;(##)"));
Console.WriteLine(pos.ToString("##;(##)"));
Would print
(16)
16
 
Share this answer
 
How about:

C#
decimal d = -556445.90m;
string s = d < 0 ? "(" + (-d).ToString() + ")" : d.ToString();


Cheers

Andi
 
Share this answer
 
Comments
[no name] 2-Jan-12 9:11am    
Brute force. Not very maintainable or elegant.
Use a format specifier, such as

C#
decimal d = -556445.90;
string s = (d*-1).ToString("(f)");


Standard Numeric Format Strings[^]
 
Share this answer
 
v3
Here is another way
Console.WriteLine("(" + Math.Abs(-15.058e18) + ")");
 
Share this answer
 
Comments
[no name] 2-Jan-12 16:31pm    
Same as #3, brute force string concatenation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900