Can you convert an array of strings to a double array without concatenating the decimal numbers in the conversion?

Asked

Viewed 50 times

-2

I would like that, somehow, after converting the string array to double, the values remain floating point. I put the input as, for example, 5.5 6.5 7.8 2.5 6.2, and during the conversion is not taken into account that are numbers with decimal place, they are concatenated and turns 55, 65, 78, 25 and 62.

I have tried the conversion in several ways. My ultimate goal was to accumulate the values summed into one variable.

string[] notas = new string[5];
Console.WriteLine("Informe 5 notas: ");
notas = Console.ReadLine().Split(' ');

for (int i = 0; i < entradas.Length; i++)
{
  soma += Convert.ToDouble(entradas[i]); // a soma da errado pq considera os números concatenados
}
string[] notas = new string[5];
Console.WriteLine("Informe 5 notas: ");
notas = Console.ReadLine().Split(' ');

double[] vetor = notas.Select(Convert.ToDouble).ToArray(); // double[] vetor = Array.ConvertAll(notas, Convert.ToDouble);

for (int i = 0; i < notas.Length; i++)
{
  soma += vetor[i]; // a soma da errado pq considera os números concatenados, não com o ponto flutuante
}

1 answer

1


The Convert.ToDouble considers the culture, as you did not inform a culture as a parameter will be used the one configured globally (in the operating system or some global configuration for the application or for VM). You probably have the English culture (where the decimal separator is comma) and are entering the entry using point as separator (or vice versa).

If culture treatment doesn’t matter much to you (it seems to be an application for study purposes) it is possible to use CultureInfo.InvariantCulture and consider the point as the decimal divider.

This will work for both codes posted.

string[] notas = new string[5];
Console.WriteLine("Informe 5 notas: ");
notas = Console.ReadLine().Split(' ');

double soma = 0;
for (int i = 0; i < notas.Length; i++)
{
    soma += Convert.ToDouble(notas[i], CultureInfo.InvariantCulture); 
}

Console.WriteLine(soma);

Note that the best type of data to store notes is decimal and not double. You can see a little more about this in:

  • Thank you for the reading instructions and for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.