Reputation: 25
I am trying to take output from an array and convert to a double for use in a calculation.
This is what I am trying to do:
Console.WriteLine(product[1]);
double units = Convert.ToDouble(Console.ReadLine());
Have been trying few other thing but getting no where; any easy solution?
Upvotes: 0
Views: 741
Reputation: 914
If you need to convert the whole array to doubles, you could do this:
using System.Linq;
var doubleProduct = product.Select(p => double.Parse(p)).ToArray();
You can also use Array.ConvertAll()
which is apparently more efficient (Thanks @PetSerAl for the tip). It also means you don't need Linq:
var doubleProduct = Array.ConvertAll(product, p => double.Parse(p));
Upvotes: 2
Reputation: 6066
Please try folllowing:
using System;
public class Program
{
public static void Main()
{
string[] products= { "10.5","20.5","50.5"};
foreach (var product in products)
{
Console.WriteLine(Convert.ToDouble(product));
}
}
}
Upvotes: 0
Reputation: 7556
your line could be throw exception if the user type some invalid double
double units = Convert.ToDouble(Console.ReadLine());
you should do this
double units ;
if (!double.TryParse(Console.ReadLine(), out units )) {
//units is not a double
}
else{
//units is a double
}
Upvotes: 2
Reputation: 2393
using System;
public class Example
{
public static void Main()
{
string[] values= { "-1,035.77219", "1AFF", "1e-35",
"1,635,592,999,999,999,999,999,999", "-17.455",
"190.34001", "1.29e325"};
double result;
foreach (string value in values)
{
try {
result = Convert.ToDouble(value);
Console.WriteLine("Converted '{0}' to {1}.", value, result);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a Double.", value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is outside the range of a Double.", value);
}
}
}
}
// The example displays the following output:
// Converted '-1,035.77219' to -1035.77219.
// Unable to convert '1AFF' to a Double.
// Converted '1e-35' to 1E-35.
// Converted '1,635,592,999,999,999,999,999,999' to 1.635593E+24.
// Converted '-17.455' to -17.455.
// Converted '190.34001' to 190.34001.
// '1.29e325' is outside the range of a Double.
Read MSDN
Console.WriteLine Method (String, Object)
Upvotes: 1
Reputation: 543
There's no need to write it to console and read it back.. simply:
var units = Convert.ToDouble(product[1]);
You might also consider using Double.TryParse() to check whether the value can be converted into a double and isn't a string of letters.
Upvotes: 2