简体   繁体   中英

Input string was not in a correct format retriving value from label

string labeldistance = lbldistance.Text;
string output = Regex.Match(labeldistance, @"\d+").Value;
double labeldistance1 = Convert.ToDouble(output);
double carMilege = 10;
double cost = 70;
lblResult.Text = ((labeldistance1/carMilege)*cost).ToString();

retrieving value from label and label contains both string and integer

You Need to first make your string an int

   string labeldistance = lbldistance.Text;
   labeldistance.ToInt32();
   string output = Regex.Match(labeldistance, @"\d+").Value;
   double labeldistance1 = Convert.ToDouble(output);

EDIT: If you need it to a float just do the same thing, just

  labeldistance.ToFloat();

Regarding the error:

Input string was not in a correct format retriving value from label

This error appears when the input string to Convert.ToDouble() contains no numbers so in your program, output definitely does not have any numbers.

Convert.ToDouble(""); // throws System.FormatException: Input string was 
                      // not in a correct format.

Convert.ToDouble("48.1") // works fine

So you should debug, set a breakpoint and check if lbldistance.Text really contains '48.1km', and then if output contains 48.

Extracting the number using regex:

As per your example, it looks like you want to extract 48.1 using the double variable. For that you might want to tweak you regex like this:

\d+(.\d+)?

This will capture numbers containing decimals too. Here's a working demo using this regex and parts of your code:

string labeldistance = "48.1km";
string output = Regex.Match(labeldistance, @"\d+(.\d+)?").Value;
double labeldistance1 = Convert.ToDouble(output);
Console.WriteLine(labeldistance1);
// Outputs 48.1

Dotnet Fiddle

So if you can ensure lbldistance.Text really contains 48.1km then using the above regex you should be able to get your desired output.

Hope this helps!

Always sanitize input you get from the user:

using System;
using System.Text.RegularExpressions;

namespace StackOverflow_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            const string input = "Label: +1,234.56";
            string sanitized = Regex.Match(input, @"[0-9\.\+\-\,]+").Value; // filters out everything except digits (0-9), decimal points (.), signs (+ or -), and commas (,)
            double distance = Convert.ToDouble(sanitized);

            Console.WriteLine($"Input => \t\t{input}");             // Label: +1,234.56
            Console.WriteLine($"Standardized => \t{sanitized}");    // +1,234.56
            Console.WriteLine($"Distance => \t\t{distance}");       // 1234.56
            Console.ReadKey();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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