[英]C# convert string array output to double
我正在尝试从数组中获取输出,并转换为用于计算的双精度型。
这就是我想要做的:
Console.WriteLine(product[1]);
double units = Convert.ToDouble(Console.ReadLine());
一直在尝试其他事情,但没有成功。 任何简单的解决方案?
无需将其写入控制台并读回。
var units = Convert.ToDouble(product[1]);
您可能还考虑使用Double.TryParse()来检查该值是否可以转换为双精度值,并且不是字母字符串。
如果用户键入一些无效的double,则您的行可能会引发异常
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
}
如果需要将整个数组转换为双精度数组,则可以执行以下操作:
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));
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
请尝试以下:
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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.