简体   繁体   中英

Floating Point fixed length Number formatting c#

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

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

In modern .NET 5.0+ you don't need to call string.Format directory. Instead, use $ in front of your string, and delimit variables with {..}

double float1 = 100.0;
double float2 = 0.2;
Debug.WriteLine($"{float1:##0.00}");    // 100.00
Debug.WriteLine($"{float2:##0.00}");    // 0.20

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