简体   繁体   中英

c# ToString a decimal and force + sign AND number decimal places

How can I do two things in tostring format:

1. Display number to x decimal places
2. Also force a + sign so that negative an positive numbers lineup in nice columns.

string fmt = "+N" + dp + ";-N" + dp;
Console.WrtieLine(Open.ToString(fmt))

Does not work?

You'll need to create a custom format string to do what you want. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx tells you about these but the below is a quick example of one thing that does the trick.

double num = 1111.019123;
int dp = 2;
string format = String.Format("+#.{0};-#.{0}",new string ('#',dp));
Console.WriteLine(num.ToString(format));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM