简体   繁体   English

C#从字符串中解析值

[英]C# parse value from string

I would like to parse string value like this : 我想像这样解析字符串值:

.02234 
-.23455 
-1.23345 
2. 
.3 

but i get an FormatException 但我得到一个FormatException

 for (int i = 1; i < 7; i++)
 {
     var item =  Double.Parse(reader.ReadLine(44).Substring(8 * i, 8));
     richTextBox1.Text += item.ToString() + "\n";  
 }

在此输入图像描述

the problem that i should convert this numbers like "0.2" or "-.0541" to double or any value type to work with it !!! 我应该将这个数字转换为“0.2”或“-0.541”以加倍或任何值类型来解决它的问题!

You're passing a string that isn't a double, something like 1.a or 1. .3 (1 string representing 2 numbers) 你传递的字符串不是双1.a ,比如1.a1. .3 (1个字符串代表2个数字)

You can use Double.TryParse() and it will not throw an exception but return true/false if it was successful or not. 您可以使用Double.TryParse() ,它不会抛出异常,但如果成功与否则返回true / false。 It might make the flow easer. 它可能使流动更容易。

Since you've made a comment that , is the decimal separator in your locale, there is a better option than doing a string-replace of . 既然你已经有了一个评论说,在语言环境的小数点分隔符,还有比这样的字符串替换一个更好的选择. to , ; , tell the Double.Parse() method to use a different number format. 告诉Double.Parse()方法使用不同的数字格式。

See the MSDN doc for Parse(String s) . 请参阅MSDN doc for Parse(String s) Especially, note the following: 特别注意以下几点:

The s parameter is interpreted using the formatting information in a NumberFormatInfo object that is initialized for the current thread culture. 使用为当前线程文化初始化的NumberFormatInfo对象中的格式信息来解释s参数 For more information, see CurrentInfo. 有关更多信息,请参阅CurrentInfo。 To parse a string using the formatting information of some other culture, call the Double.Parse(String, IFormatProvider) or Double.Parse(String, NumberStyles, IFormatProvider) method. 要使用其他文化的格式信息解析字符串,请调用Double.Parse(String,IFormatProvider)或Double.Parse(String,NumberStyles,IFormatProvider)方法。

Assuming your current thread culture is using a number format that considers , to be the decimal separator (French/France fr-FR , for example), you must pass an IFormatProvider to the Parse() method that defines . 假设你当前线程培养使用考虑的数字格式,以小数点分隔符(法国/法国fr-FR ,例如),则必须通过IFormatProviderParse()定义方法. as the decimal separator. 作为小数点分隔符。 Conveniently, the "no culture in particular" culture, CultureInfo.InvariantCulture , does just this. 方便的是,“没有文化特别”的文化, CultureInfo.InvariantCulture就是这样做的。

So this code should parse successfully: 所以这段代码应该成功解析:

for (int i = 1; i < 7; i++)
{
    // Assume the substring of ReadLine() contains "-.23455", for example
    var item = Double.Parse(reader.ReadLine(44).Substring(8 * i, 8), CultureInfo.InvariantCulture);
    richTextBox1.Text += item.ToString() + "\n";  
}
reader.ReadLine(44).Substring(8 * i, 8).ToString()

You won't need the .ToString(). 您不需要.ToString()。 Verify that this actually returns the value you're looking for. 验证这实际上返回了您正在寻找的值。

The format exception is throw because the value it's trying to parse is not valid! 格式异常是throw,因为它尝试解析的值无效! My first guess is that the argument you're passing is not in fact a double. 我的第一个猜测是你传递的论点实际上不是双重的。

Might try to split up your calls, and toss in a breakpoint to see what's actually going on. 可能会尝试拆分你的电话,并在断点处查看实际发生的情况。

 for (int i = 1; i < 7; i++)
 {
     string textNum = reader.ReadLine(44).Substring(8 * i, 8);
     // add a breakpoint on the next line, then look at textNum. I bet it's not what you hoped.
     double item =  double.Parse(textNum);
     richTextBox1.Text += string.Format("{0}\n", item);  
 }

Use Double.TryParse() and test to see if the value was successfully parsed into your local variable like this: 使用Double.TryParse()并测试以查看该值是否已成功解析为您的局部变量,如下所示:

for (int i = 1; i < 7; i++)
{
    double value = 0;
    string input = reader.ReadLine(44).Substring(8 * i, 8);

    if (Double.TryParse(input, out value))
    {
        richTextBox1.Text += value.ToString() + "\n";  
    }
    else
    {
        richTextBox1.Text = "Invalid double entered.";
    }
}

i just find a solution to the problem ( replace to dot with comma ) : 我只是找到问题的解决方案(用逗号代替点):

    public Double[] GridValues(int fromline) 
    {
        Double[] values = new Double[7];
        for (int i = 1; i < 7; i++)
        {
            string input = ReadLine(fromline).Substring(8 * i, 8).Replace(".", ",");
            values[i-1] = double.Parse(input);
        }

        return values;
    }

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

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