Reputation: 31
I'm trying to get double values from Excel to my C# project. But, when I try that, Visual Studio automatically erases the comma/period, and shows the number without them.
For Example:
Excel: 192,168 or 192.168
C#: 192168,00
How can I prevent this from happening?
Excel Get-Value Code:
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
{
tsp.addArray(Convert.ToDouble(ds.Tables["Deneme"].Rows[i][j].ToString()), i, j);
}
}
Upvotes: 1
Views: 2872
Reputation:
Replace is good way to do it i guess.
Just try like that.
string oldString = ds.Tables["Deneme"].Rows[i][j].ToString(); // Old string in addArray.
string convertedString = oldString.Replace(".",","); // Replacer for dots.
double convertedDouble = Convert.ToDouble(convertedString); // Convert double now.
Upvotes: 3
Reputation: 98750
I think your culture is tr-TR
that's why your NumberDecimalSeparator
is ,
not .
That's why when you write 192.168 in your program, it read its as hundred and ninety-two thousand ... but when you write 192,168 hundred and ninety-two ...
If your excel cell is like 192,168
, there is no problem. Convert.ToDouble
works exactly as you want;
string s = "192,168";
double d = Convert.ToDouble(s, CultureInfo.GetCultureInfo("tr-TR"));
Console.WriteLine(d); //192,168
But if your excel cell is like 192.168
, then you need to use n0
format like;
string s = "192.168";
double d = 0;
if(s.Contains("."))
{
d = Convert.ToDouble(s, CultureInfo.GetCultureInfo("tr-TR"));
}
Console.WriteLine(d.ToString("n0")); //192.168
Upvotes: 1