2

I have a data-table with data. I need to add another column to the datatable having the same value of another column but with less precision.

Ie the original column would be having value 12.123 but the new column will have value 12.12

What is the best way to do this?

madth3
  • 7,275
  • 12
  • 50
  • 74
Ananth
  • 10,330
  • 24
  • 82
  • 109

2 Answers2

4

Something like this

            yourDataTable.Columns.Add("newCol", typeof(double));

            foreach (System.Data.DataRow row in yourDataTable.Rows)
            {
                row["newCol"] = Math.Round(Convert.ToDouble(row["oldCol"]), 2);                    
            }
RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • Thanks! I used your example to add a new, non-computed column to an existing table `sectionDS.Tables[0].Columns.Add("IPAddr", typeof(long)); foreach (DataRow row in sectionDS.Tables[0].Rows) { row["IPAddr"] = 0x0100007F; }` – Jim Lahman Aug 27 '12 at 13:44
1

Some grid implementations, like DevExpress XtraGrid, allow you to have unbound columns and easily provide values for them. The same thing would involve some hacking with a basic DataGridView, so I have an other suggestion. Add a new read-only property to your class: decimal value1 { get; set; } decimal value2 { get { return Math.Round(value1, 2); } } This way you don't even have to bother with the column display format.

fejesjoco
  • 11,763
  • 3
  • 35
  • 65
  • Thanks..But I am not binding this data table to any grid view. Iam just using this for some calculations hence I dont think this solution will work here. – Ananth Dec 23 '10 at 09:18