开发者

Right align currency in string format

开发者 https://www.devze.com 2023-04-04 18:08 出处:网络
I\'m trying to align some currency to the right: double number1 = 150.45; double number2 = 1400.95; //Outputkr. 150,开发者_Go百科45

I'm trying to align some currency to the right:

double number1 = 150.45;
double number2 = 1400.95;

//Output  kr. 150,开发者_Go百科45
Console.WriteLine("{0:c2}", number1);

//Output  kr. 1.400,95
Console.WriteLine("{0:c2}", number2);

But I want my output to look like this.

//Output kr.   150.45

//Output kr. 1.400,95

Where the number is aligned to the right?


 string sym = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
 Console.WriteLine("{0}{1,10:#,##0.00}",sym, number1);
 Console.WriteLine("{0}{1,10:#,##0.00}",sym, number2);

ideone output


it's rather hard for the system to say how many places your numbers have. So you have to decide this yourself. If you have decided you can use something like String.PadLeft

For example

Console.WriteLine("kr. {0}", number1.ToString("#,##0.00").PadLeft(10,' '));


This should work for any culture:

int width = 20;

string result = 1400.95.ToString("C");

NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
if (nfi.CurrencyPositivePattern % 2 == 0)
{
    result = nfi.CurrencySymbol +
             result.Substring(nfi.CurrencySymbol.Length).PadLeft(width);
}
else
{
    result = result.PadLeft(width + nfi.CurrencySymbol.Length);
}

// result == "$            1,400.95" (en-US)
//           "£            1,400.95" (en-GB)
//           "           1.400,95 €" (de-DE)
//          "           1.400,95 kr" (sv-SE)
//         "              1.401 kr." (is-IS)
//          "kr            1 400,95" (nb-NO)
//         "kr.            1.400,95" (da-DK) (!)


Sure this isn't as good as the accepted answer, but I had the same problem with right-alignment and my immediate reflex was to:

//Output  kr. 150,45
Console.WriteLine("{0,10}",string.Format("{0:c2}",number1));
0

精彩评论

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