Floating Point fixed length Number formatting c#

笑着哭i 提交于 2021-02-05 09:40:58

问题


I want to format a floating point number as follows in C# such that the entire width of the floating point number in C# is a fixed length (python equivalent format specifier 6.2f) I do NOT want it to be padded with 0's on the left but padded with a white space

100.00
 90.45
  7.23
  0.00

what I have tried so far

string.Format({0:###.##},100); 
string.Format({0:###.##},90.45);
string.Format({0:###.##},7.23);
string.Format({0:###.##},0.00);

but the output is incorrect

100
90.45
7.23
      //nothing is printed

I have also gone through this but am unable to find a solution. I am aware of the string.PadLeft method, but I am wondering if there is a more proper way than

(string.format({0,0.00},number)).PadLeft(6," ")

EDIT I am specifically asking if there is a correct inbuilt method for the same, not if it can be done with same mathematical wizardry


回答1:


If you always want 2 digits after the decimal, you can specify 00 in the format specifier. You would need to use a right aligned field width also (I used 6 as the max field width).

Try this:

void Main()
{
    Console.WriteLine(string.Format("{0,6:##0.00}",100.0)); 
    Console.WriteLine(string.Format("{0,6:##0.00}",90.45));
    Console.WriteLine(string.Format("{0,6:##0.00}",7.23));
    Console.WriteLine(string.Format("{0,6:##0.00}",0.00));
}

In LinqPad it outputs:

100.00
 90.45
  7.23
  0.00


来源:https://stackoverflow.com/questions/51826293/floating-point-fixed-length-number-formatting-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!