简体   繁体   English

如何在C#中将字符串转换为double

[英]How to convert string to double in C#

In the following code , rating in generating error在下面的代码中,产生错误的等级

string[] allLines = File.ReadAllLines(@"Ratings.csv");

var parsed = from line in allLines
            let row = line.Split(';')
             select new
             {
                 UserId = row[0],
                 ItemId = row[1],
                 rating = row[3]
            };
var Rating = parsed.Select(x => new AddRating (x.UserId, x.ItemId,x.rating));

client.Send(new Batch(Rating));


var detailViews = parsed.Select(x => new AddDetailView(x.UserId, x.ItemId,x.rating ));
String st = "85.78";
Double db = Convert.ToDouble(st);

//Or With Error Hndler

try
        {
            string st = "85.78";
            Double db = Convert.ToDouble(st);
        }
catch (FormatException)
        {

            // Your error handler 

        }

The exception is telling you what the issue is.例外是告诉您问题是什么。 Your constructor is expecting doubles, and you're passing it strings.您的构造函数期待双打,而您正在传递字符串。 In order to fix it, you've gotta parse your string inputs into doubles.为了修复它,您必须将字符串输入解析为双精度。

The way your code is written, you'll have to change the way you're using the .Select statement in order to parse it in a decent error handling manner.编写代码的方式,您必须更改使用.Select语句的方式,以便以适当的错误处理方式解析它。

I'd suggest swapping the .Select for a foreach , then parsing each property, then instantiating your class.我建议将.Select交换为foreach ,然后解析每个属性,然后实例化您的类。

foreach (var item in parsed)
{
    double userId = 0;
    double itemId = 0;
    double rating = 0;
    double.TryParse(item.UserId, out userId);
    double.TryParse(item.ItemId, out itemId);
    double.TryParse(item.rating, out rating);

    var rating = new AddRating(userId, itemId, rating);
    //**** do whatever you want with the new object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM