Domanda

Mi piacerebbe conoscere il modo più semplice per formattare una stringa come stile di contabilità. So come formattare come valuta utilizzando {0: c} ma ci sono alcune differenze di stile di contabilità, per esempio, tutti i segni del dollaro si allineeranno così come tutti i punti decimali e negativi sono espressi tra parentesi piuttosto che con un "-" segno meno. È possibile trovare un buon esempio del modo in cui vorrei in Excel se si formatta le celle come "contabile" con 2 cifre decimali.

È stato utile?

Soluzione

Ignorando le vostre esigenze di allineamento, è possibile utilizzare

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

per racchiudere i numeri negativi.

Per allineare i numeri, che avrebbe dovuto formattare senza il simbolo di valuta, ed il rilievo i numeri formattati te stesso con gli spazi, utilizzando un font a larghezza fissa renderebbe questo lavoro più facile per voi.

EDIT:

Sembra String.Format è tuo amico:

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

dove 15 è la larghezza totale della produzione, ed è necessario per aggiungere questo testo per il vostro simbolo di valuta. (Di nuovo, questo allinea solo larghezza fissa)

Altri suggerimenti

Non c'è scorciatoia stringa di formato (quelli a singolo carattere con regole predefinite) per la gestione di formati di stile di contabilità ( qui c'è un foglietto con le stringhe di formato disponibili ) quindi dovrete scrivere un più specifico (come la risposta di Patrick) o il proprio metodo di analisi.

I requisiti di allineamento sarebbe specifica per come li sta visualizzando. Sto assumendo che si sta utilizzando una tabella, nel qual caso si è limitato da ciò che HTML sostiene, e non supporta gli allineamenti stile di contabilità come Excel.

questo blog ci sono stati alcuni varie formati delineati e questo sembrava essere vicino a quello che stavate cercando:

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)"

Non gestire l'imbottitura (potrebbe essere necessario riparare quello voi stessi), ma ha la giusta parentesi.

Si potrebbe fare qualcosa utilizzando una variante del metodo di Patrizio. In questo modo di gestire la formattazione e l'allineamento supponendo che si conosce il limite superiore di quanto grande di un valore che si tratta di:

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, ' ');
}

Ecco un semplice esempio app per vederlo formato:

    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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top