C # double decimal alignment formatting

I align numbers with different numbers of decimals so that the decimal is aligned in a straight line. This may be caused by spaces, but I have problems.

Says I want to align the following digits: 0 0.0002 0.531 2.42 12.5 123.0 123172

This is the result that I get after:

0 0.0002 0.531 2.42 12.5 123.0 123172 
+6
double c # formatting
source share
2 answers

If you want to get exactly this result, you can not use the formatting of numerical data, since it does not format 123 as 123.0 . You should consider values ​​as strings to preserve trailing zero.

This gives you exactly the result you requested:

 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 
+5
source share

You can use the string.format or ToString method to do this twice.

 double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0; string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: $19.95. MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: ($19.95). // The minus sign is omitted by default. MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero"); // In the US English culture, MyString has the value: Zero. 

this article from msdn can help you if you need more information

-2
source share

All Articles