简体   繁体   English

c#ToString一个十进制和强制+符号和数字小数位

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

How can I do two things in tostring format: 我怎么能用tostring格式做两件事:

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. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx告诉你这些,但下面是一个快速举例说明一件事。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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