C# 从标签检索值时,输入字符串的格式不正确
您需要首先将字符串设置为intC# 从标签检索值时,输入字符串的格式不正确,c#,asp.net,C#,Asp.net,您需要首先将字符串设置为int 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)
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();
编辑:如果你需要它成为一个浮动,只要做同样的事情,只要
string labeldistance = lbldistance.Text;
labeldistance.ToInt32();
string output = Regex.Match(labeldistance, @"\d+").Value;
double labeldistance1 = Convert.ToDouble(output);
关于错误: 从标签检索值时,输入字符串的格式不正确 当
Convert.ToDouble()
的输入字符串不包含任何数字时,会出现此错误,因此在程序中,output
肯定没有任何数字
labeldistance.ToFloat();
因此,您应该调试、设置断点并检查lbldistance.Text
是否真的包含“48.1km”,然后检查output
是否包含48
使用正则表达式提取数字:
根据您的示例,您似乎希望使用双变量提取48.1。为此,您可能希望对regex进行如下调整:
Convert.ToDouble(""); // throws System.FormatException: Input string was
// not in a correct format.
Convert.ToDouble("48.1") // works fine
这也将捕获包含小数的数字。下面是使用此正则表达式和部分代码的工作演示:
\d+(.\d+)?
因此,如果您可以确保lbldistance.Text确实包含48.1km,那么使用上述正则表达式,您应该能够获得所需的输出
希望这有帮助 始终清理从用户处获得的输入:
string labeldistance = "48.1km";
string output = Regex.Match(labeldistance, @"\d+(.\d+)?").Value;
double labeldistance1 = Convert.ToDouble(output);
Console.WriteLine(labeldistance1);
// Outputs 48.1
你的问题是什么?你想把一个字符串转换成一个double。那绳子呢,当你想把它做成双人的时候,它不容易合身?另外,请回答您的问题,以便出现错误,而不仅仅是屏幕截图。请避免链接到代码或错误的图片。相反,直接将错误粘贴到帖子中。检查输出值。其中有无法转换的内容。该错误意味着传递给
Convert.ToDouble
的值无法转换。字符串输出的值是多少?我刚看到你的评论,标签中不能有“km”。它不是一个数字,因此不能转换为float/int@Ghanshyam Kumarthanks来回答我的问题。标签生成字符串和整数的值,例如-45.6km,34.1km。。。。。我想把45.6公里转换成45.6公里,然后使用lblresult.txtook中的值,那么你缺少的是一个可以捕获小数的部分。您需要labeldistance,@“\d+(.\d+)”
。然后输出它。
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();
}
}
}