C#将字符串数组输出转换为double

时间:2014-12-19 09:35:20

标签: c# arrays string double output

我正在尝试从数组中获取输出并转换为double以用于计算。

这就是我想要做的事情:

Console.WriteLine(product[1]);
double units = Convert.ToDouble(Console.ReadLine());

一直在尝试其他一些事情,但没有在哪里;任何简单的解决方案?

5 个答案:

答案 0 :(得分:2)

没有必要将它写入控制台并将其读回..简单地说:

var units = Convert.ToDouble(product[1]);

您也可以考虑使用Double.TryParse()来检查该值是否可以转换为double并且不是一串字母。

答案 1 :(得分:2)

如果用户键入一些无效的双重

,您的行可能会抛出异常
double units = Convert.ToDouble(Console.ReadLine());

你应该这样做

double units ;
if (!double.TryParse(Console.ReadLine(), out units )) {
    //units is not a double
}
else{
  //units is a double
}

答案 2 :(得分:2)

如果您需要将整个数组转换为双精度数,则可以执行以下操作:

using System.Linq;

var doubleProduct = product.Select(p => double.Parse(p)).ToArray();

修改

你也可以使用显然效率更高的Array.ConvertAll()(感谢@PetSerAl提示)。这也意味着你不需要Linq:

var doubleProduct = Array.ConvertAll(product, p => double.Parse(p));

答案 3 :(得分:1)

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.

阅读MSDN

Console.WriteLine Method (String, Object)

Console.ReadLine Method

答案 4 :(得分:0)

请尝试以下:

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));
        }           
    }
}

Live Demo