Oddity with ToString() custom number formatting
https://stackoverflow.com/questions/934260
Question
I am trying to convert numbers in the form 123456 to 123,456 which I find easy enough by using the .NET ToString() method with a custom format of N0.
However in one case of data I am getting strange formats whilst using this method.
In this case I am generating a DataTable dynamically for my input table to test the code.
DataTable dt = new DataTable();
dt.Columns.Add("Cases", typeof(Int32));
For example my data looks like this before formatting is applied.
-------------------------------------------- | Cases | 2495 | 3937 | 3207 | 4173 | 4265 | --------------------------------------------
I would like it to look like this.
------------------------------------------------- | Cases | 2,495 | 3,937 | 3,207 | 4,173 | 4,265 | -------------------------------------------------
I try formatting it by using code like so.
output.Rows[r][c] = Convert.ToInt32(input.Rows[c - 1][r + 1]).ToString("N0");
(Note: The reason for the strange formatting is because I am taking a DataTable and transposing it to another DataTable.)
Using the above formatting I now get the following data returned.
-------------------------------------------------------------------------- | Cases | 01/02/0495 | 01/03/0937 | 01/03/0207 | 01/04/0173 | 01/04/0265 | --------------------------------------------------------------------------
I then tried it with one decimal point using:
output.Rows[r][c] = Convert.ToInt32(input.Rows[c - 1][r + 1]).ToString("N01");
Which gave me the following result.
------------------------------------------------------ | Cases | 2495.0 | 3937.0 | 3207.0 | 4173.0 | 4265.0 | ------------------------------------------------------
This has now confused me because it is accepting the fact that the number can be formatted this way.
The next thing I tried was different ways of formatting strings like so.
output.Rows[r][c] = string.Format("{0:N0}", input.Rows[c - 1][r + 1]);
output.Rows[r][c] = Convert.ToInt32(input.Rows[c - 1][r + 1]).ToString("#,##0");
None of these give the number format how I would like either. Can anybody advise where I am going wrong? Is it so simple that I have missed the point?
Solution
It looks to me simply that you've set the data-type of the columns in the DataTable
incorrectly. Try making it explicit as an int
(it looks like DateTime
at the moment).
Also - the job of the DataTable
is to hold data; not to disply it. You could store it pre-formatted as string
s, I guess (as long as you tell it that the columns are strings) - but if you are storing it as int
, then forget the display; as soon as you have run Convert.ToInt32
your job is over. How it appears is the job of the DataGridView
(or whatever); tell that about "N0"...