开发者

C# double formatting align on decimal sign

开发者 https://www.devze.com 2022-12-21 09:22 出处:网络
I align num开发者_高级运维bers 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.

I align num开发者_高级运维bers 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.

Lays say I want to align the following numbers: 0 0.0002 0.531 2.42 12.5 123.0 123172

This is the result I'm after:

     0
     0.0002
     0.531
     2.42
    12.5
   123.0
123172


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


While not exactly answering the question because of the trailing zeros, this aligns decimal points with 4 decimal places and a maximum of 11 characters in total.

someNumber.ToString("0.0000").PadLeft(11)

Eg. the following strings

0d.ToString("0.0000").PadLeft(11)
0.0002d.ToString("0.0000").PadLeft(11)
0.531d.ToString("0.0000").PadLeft(11)
2.42d.ToString("0.0000").PadLeft(11)
12.5d.ToString("0.0000").PadLeft(11)
123.0d.ToString("0.0000").PadLeft(11)
123172d.ToString("0.0000").PadLeft(11)

are

     0.0000
     0.0002
     0.5310
     2.4200
    12.5000
   123.0000
123172.0000

in the invariant culture.


You can use string.format or ToString method of double to do so.

double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0;

string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: $19.95.

MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. 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 U.S. English culture, MyString has the value: Zero.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号