1

I dont know how to ask, but i want to load data in double not in string as you can see in the code. Can i change them in double? i want to store them in array because i want to find maximum value from the data. cannot find them in string.

private void button1_openfile_Click(object sender, EventArgs e)
    {
        //load data from text file
        string[] lines = File.ReadAllLines(@"C:\Users\Siti Nurhazwani\Desktop\table.txt");
        string[] values;

        for (int i = 0; i < lines.Length; i++)
        {
            values = lines[i].ToString().Split('/');
            string[] row = new string[values.Length];

            for (int j = 0; j < values.Length; j++)
            {
                row[j] = values[j];
            }

            table.Rows.Add(row);
        }
        

    }

can someone share code to me how to change the string to double? please use simple terms i am a beginner in c#.

hycal99
  • 11
  • 4
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number – Peter Bons Aug 17 '21 at 06:51
  • You can use either [`double.TryParse()` or `Convert.ToDouble()`](https://stackoverflow.com/questions/586436/double-tryparse-or-convert-todouble-which-is-faster-and-safer) – John Wu Aug 17 '21 at 07:04

2 Answers2

0

I'm not sure if I understood your question correctly. Can you do the change from string to double inside the loop? If so, this should be quite easy to solve, try this for example:

var result = Convert.ToDouble(originalValue)

https://learn.microsoft.com/en-us/dotnet/api/system.convert.todouble?view=net-5.0

  • i try but error, its say " System.InvalidCastException: Unable to cast object of type System.String[] to type System.IConvertible '.' .. What should i do? – hycal99 Aug 17 '21 at 08:40
  • You cannot directly convert string[] to double. But to convert each element of the array. for (int i = 0; i < lines.Length; i++) { var value= Convert.ToDouble(lines[i]); } And Siva Makani has provided more detailed code. – DanielZhang-MSFT Aug 18 '21 at 01:52
0

Change these lines in your code to double.

string[] row = new string[values.Length];

for (int j = 0; j < values.Length; j++)
{
    row[j] = values[j];
}

Instead

double[] row = new double[values.Length];

for (int j = 0; j < values.Length; j++)
{
   row[j] = Convert.ToDouble(values[j]);
}
Siva Makani
  • 196
  • 2
  • 17