C# double formatting align on decimal sign

前端 未结 2 2085
萌比男神i
萌比男神i 2021-01-05 19:36

I align numbers with various number of decimals so that the decimal sign aligns on a straight row. This can be achevied by padding with spaces, but I\'m having trouble.

2条回答
  •  日久生厌
    2021-01-05 20:23

    If you want exactly that result you can't use any formatting of numerical data, as that would not format 123 as 123.0. You have to treat the values as strings to preserve the trailing zero.

    This gives you exactly the result that you asked for:

    string[] numbers = { "0", "0.0002", "0.531", "2.42", "12.5", "123.0", "123172" };
    
    foreach (string number in numbers) 
    {
        int pos = number.IndexOf('.');
        if (pos == -1) 
            pos = number.Length;
        Console.WriteLine(new String(' ', 6 - pos) + number);
    }
    

    Output:

         0
         0.0002
         0.531
         2.42
        12.5
       123.0
    123172
    

提交回复
热议问题