C# 异常解析.Double

标签 c# math

我有一个简单的 C# Web 控制台应用程序,它利用 HTML Agility Pack 从给定网站检索数据。我的代码从表单字段中获取一个值并尝试将其重构为英寸,代码有效!但是我想知道是否有更正确、更简单的方法来实现我的目标?

string MetricName = "686 x 1981mm, 35mm Thick: £143.01";

var priceGrab = MetricName.Substring(MetricName.LastIndexOf('£') + 1);
// 25.4 is what we divide the MM value by to get the inch value
const double imp = 25.4;

Match firstMeasurements = Regex.Match(MetricName, @"\d+");
Match secondMeasurements = Regex.Match(MetricName, @"x([^,]*)");
Match thicknessMeasurements = Regex.Match(MetricName, @",([^mm]*)");

string firstM = firstMeasurements.Value;

//Convert MM to Inches
double first = double.Parse(firstM) / imp;

string secondM = secondMeasurements.Value;
Match secondFixed = Regex.Match(secondM, @"\d+");
string secondM1 = secondFixed.Value;

//Convert MM to Inches
double second = double.Parse(secondM1) / imp;

string thicknessM = thicknessMeasurements.Groups[1].Value;
Match thirdFixed = Regex.Match(thicknessM, @"\d+");

//Convert MM to Inches
double three = double.Parse(thicknessM) / imp;

ImperialVariant = string.Format("{0} x {1}\", {2}\" Thick: £{3}",first.ToString("00"), second.ToString("00"), three.ToString("0.00"), priceGrab);

return ImperialVariant;

ImperialVariant 将等于:

30 x 78", 1.38" Thick: £143.01

我的程序出于未知原因引发了以下异常。

at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s)

有人能对此提供一些反馈吗??

谢谢

最佳答案

这有点令人困惑,因为尝试执行您的代码不会产生任何异常。然而,

I was wondering if there was a more correct, simpler way of achieving my goal

我建议简化正则表达式,对 float 使用 Decimal,使用格式说明符格式化输出并确保在解析时使用正确的 CultureInfo和格式:

String ConvertToImperial(String text) {
  var regex = new Regex(@"^(?<first>\d+)\s*x\s*(?<second>\d+)mm,\s*(?<third>\d+)mm Thick: £(?<price>\d+\.\d+)$");
  var match = regex.Match(text);
  if (!match.Success)
    return null;
  var first = Int32.Parse(match.Groups["first"].Value);
  var second = Int32.Parse(match.Groups["second"].Value);
  var third = Int32.Parse(match.Groups["third"].Value);
  var price = Decimal.Parse(match.Groups["price"].Value, CultureInfo.InvariantCulture);
  return String.Format(
    CultureInfo.InvariantCulture,
    @"{0:F0} x {1:F0}"", {2:F2}"" Thick: £{3:N2}",
    ConvertToInches(first),
    ConvertToInches(second),
    ConvertToInches(third),
    price
  );
}

Decimal ConvertToInches(Decimal mm) {
  return mm/25.4M;
}

如果输入字符串中提供了一些非常大的数字,此代码仍然会抛出异常。

关于C# 异常解析.Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543820/

相关文章:

c# - 为什么要将 2 类的引用放入 1 类的对象中?

c# - 复杂的正则表达式验证器

c# - CancelAsync 是否有效?

math - 摄像机平移向量-与旋转矩阵的关系

python - 在 Sympy 中收集类似的表达式

c# - 正则表达式匹配方括号内括号内的数字和可选文本

c# - 理解 MVVM 中的分离

math - 如何从等式中得到 Radon 变换伪代码

javascript - 玩具箱挑战 - 电子商务装运/容器拆分

math - 编程是数学的子集吗?