以下代码,我从网站下载信息。在这个例子中,我想提取信息并将结果存储在名为myInfo的double变量中。在此示例中,文本中的信息:" 10,000.00"。我需要将其转换为double并将信息存储在变量myInfo中。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;
using System.Globalization;
using System.Net;
using System.IO;
using HtmlAgilityPack;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string url = "http://www.eurexchange.com/exchange-en/products/idx/stx/blc/19068!quotesSingleViewOption?callPut=Call&maturityDate=201412";
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var pricesAndQuotesDataTable = (from elem in document.DocumentNode.Descendants()
.Where(d =>
d.Attributes["class"] != null && d.Attributes["class"].Value == "toggleTitle" &&
d.ChildNodes.Any(h => h.InnerText != null && h.InnerText == "Prices/Quotes"))
select elem.Descendants()
.FirstOrDefault(
d => d.Attributes["class"] != null && d.Attributes["class"].Value == "dataTable")).FirstOrDefault();
if (pricesAndQuotesDataTable != null)
{
var dataRows = from elem in pricesAndQuotesDataTable.Descendants()
where elem.Name == "tr" && elem.ParentNode.Name == "tbody"
select elem;
foreach (var row in dataRows)
{
var dataColumns = (from col in row.ChildNodes.Where(n => n.Name == "td")
select col).ToList();
double myInfo = double.Parse(dataColumns[0].InnerText, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo);
}
}
}
}
}
使用上面的代码,我收到一个错误:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
因此存在格式问题。但我该如何解决呢?我也尝试过使用:
double myInfo = Double.Parse(dataColumns[0].InnerText, CultureInfo.InvariantCulture);
但没有成功。 我希望它足够灵活,可以使用美国格式和欧洲格式。谢谢。
答案 0 :(得分:2)
试试这个:
var numberFormatInfo = new NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator = ".";
numberFormatInfo.NumberGroupSeparator = ",";
double result;
if (double.TryParse("10,000.00", NumberStyles.Any, numberFormatInfo, out result))
{
Console.WriteLine(result);
}
答案 1 :(得分:1)
如果您想支持多种格式,可以使用不同文化的double.TryParse
:
string[] samples = { "10,000.00", "10.000,00" };
CultureInfo deDE = new CultureInfo("de-DE"); // to support your "European format"
NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands;
foreach (string sample in samples)
{
double value;
bool parsable = double.TryParse(sample, style, NumberFormatInfo.InvariantInfo, out value);
if(!parsable)
parsable = double.TryParse(sample, style, deDE, out value);
Console.WriteLine(value); // output 10000 with both
}