Вопрос

Я хотел бы знать самый простой способ отформатировать струну в качестве стиля бухгалтерского учета. Я знаю, как форматировать как валюту с использованием {0: c}, но есть некоторые различия в стиле бухгалтерского учета, например, все знаки доллара будут выстроены так же, как и все десятичные точки, а негативы выражаются в скобках, а не с "-" Минус знак. Вы можете найти хороший пример того, как я хотел бы в Excel, если вы форматируете клетки как «учет» с 2 десятичными местами.

Это было полезно?

Решение

Игнорируя ваши требования к выравниванию, вы можете использовать

number.ToString("€#,##0.00;(€#,##0.00);Zero")

для скобки отрицательных чисел.

Чтобы выровнять свои числа, вам придется форматировать без символа валюты и наладить форматированные числа сами местами, используя шрифт с фиксированной шириной, облегчает вам эту работу.

РЕДАКТИРОВАТЬ:

Кажется, String.format - ваш друг:

String.Format("{0,15:#,##0.00 ;(#,##0.00);-   }", number)

где 15 является общей шириной вывода, и вам необходимо добавить этот текст к своему символу валюты. (Опять же, это выравнивается только по фиксированной ширине)

Другие советы

Нет никакого сочетания строки формата (однохарактерные с правилами по умолчанию) для обработки форматов стиля бухгалтерского учета (Вот шпаргалка с доступными строками формата) вам придется написать более конкретный (например, ответ Патрика) или ваш собственный метод анализа.

Требования к выравниванию будут специфичными для того, как вы их отображаете. Я предполагаю, что вы используете таблицу, и в этом случае вы ограничены тем, что поддерживает HTML, и она не поддерживает выравнивания стиля бухгалтерского учета, таких как Excel.

В этот блог были изложены несколько различных форматов, и этот, казалось, был близок к тому, что вы искали:

int neg = -10;
int pos = 10;
// C or c (Currency): It represent how many decimal place of zeros to show.
String.Format("{0:C4}", pos);      //"$10.0000"
String.Format("{0:C4}", neg);      //"($10.0000)"

Он не обрабатывает прокладку (вам, возможно, придется исправить это самостоятельно), но у него есть надлежащая скобка.

You could do something using a variation of Patricks method. This will handle formating and alignment assuming you know the upper bound of how large a value you are dealing with:

private static string OutputAsCur(decimal val)
{
    string format = "  #,##0.00 ; (#,##0.00);Zero";
    string frmt = val.ToString(format);
    return CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + frmt.PadLeft(15, ' ');
}

Here's a simple example app to see it format:

    static void Main(string[] args)
    {
        decimal d = 155.55m;

        Console.WriteLine(OutputAsCur(d));
        Console.WriteLine(OutputAsCur(d * -1));
        Console.WriteLine(OutputAsCur(1002.32m));
        Console.WriteLine(OutputAsCur(1002.32m * -1));
        Console.ReadLine();
     }

You can use a format string for String.Format to get what you're trying to accomplish. The only trick is that positive numbers, since they will not have a closing parenthesis mark, will have to incorporate a space at the end if they will be aligned with any negative numbers that will be in the column. The trick is to get that space into the string in a way that HTML will not ignore. I simply use the HTML entity   which indicates a non-breaking space in HTML.

Here's sample code. First, in the aspx.

<table>
...
    <tr>
        <th scope="row" colspan="2">Total Revenue</th>
        <td class="numeric total"><asp:Label runat="server" ID="TotalRevenueLabel" /></td>
    </tr>
...
</table>

Now, the codebehind.

public const string kMoneyFormat = "#,#.00'&nbsp;';(#,#.00);'-.--&nbsp;'";

public void DataBind()
{
    using (FinancialDataContext sql = new FinancialDataContext())
    {
        var periodQuery = from m in sql.Forecasts()
                          select m;
        ForecastsResult periodData = periodQuery.Single();
        decimal totalRevenue = period.Data.income_actual.Value + periodData.other_income.Value;
        TotalRevenueLabel.Text = totalRevenue.ToString(kMoneyFormat);
    }
}

I followed these steps for apply the "Accounting" format.

  • In a new Book on Excel, select a cell.
  • Insert data (i.e any number; for this example, add 80000).
  • Select (Accounting) NumberFormat as is shown in the screenshot #1:

Screenshot #1:

Screenshot 1

  • Select "More Number Formats".
  • Select "Custom".
  • Select any of the pre-defined formulas (see screenshot #2).

Screenshot #2:

Screenshot 2

In my case, this is the desired format for this number.


The negative side of this is that when you select the cell with the format applied on it, you wont see selected (Accounting) "in the DropDownList" Number Format.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top