简体   繁体   中英

Formatting a number string to add commas - c#

I know this question has been answered many times before however, I'm convinced the code I have is correct but isn't working correctly.

string total = ds.Tables[0].Rows[0][0].ToString();
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;

This code isn't adding the commas into my value like it desire it to.

Can anyone see why?

When you put

  string total = ds.Tables[0].Rows[0][0].ToString();

it means implicit G ("General") format string

  string total = ds.Tables[0].Rows[0][0].ToString("G");

Do not format prematurely :

  var total = ds.Tables[0].Rows[0][0];         // Value from table
  string test = string.Format("{0:N}", total); // Format total with "N" format string

Your code is trying to format a string . If the DataTable contains a number you can pass the format specifier to ToString() , eg

var test=ds.Tables[0].Rows[0][0].ToString("N");

Or store the contents in a local variable and use String.Format :

var total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);

If the datatable contains a string though, you'd have to parse it to a numeric type first

You have to use the string.Format with a number type, instead of string. In this case, the variable total is a string, it must be a number.

There are 8 overloads for the Strig.Format method. You are using this specific one: Format(String, Object) in which you pass a String value as argument of the second parameter. This is because you are using a string variable ( total ) to assign the value from the dataset in:

string total = ds.Tables[0].Rows[0][0].ToString();

Besides you are using .ToString() to retrieve it as a String .

If you are using SQL Server as data source to your ds dataset and you are certain about the SQL data type then you can assign that value directly to a variable with the corresponding C# type . To put it in a different way, SQL data types are mapped to C# data types . If you are not sure about the C# data type of ds.Tables[0].Rows[0][0] then you could simply do the following:

Object total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;

And this way you literally use the Format(String, Object) overload of String.Format .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM