问题
I actually have strings formed like this one:
{ Desc = Marketcap, Val =
1,270.10 BTC
706,709.04 USD
508,040.00 EUR
4,381,184.55 CNY
425,238.14 GBP
627,638.19 CHF
785,601.09 CAD
72,442,058.40 JPY
787,357.97 AUD
7,732,676.06 ZAR
}
I'd need to parse out all the doubles in it, and I am actually stuck with that. How may I do that?
EDIT: I actually know how many numbers I am going to parse, that's fixed, like in that string (that's just the number that changes). I don't need the notation, neither (like BTC, USD, etc)
回答1:
If your data actually looks like this:
var data = new
{
Desc = "Marketcap",
Val = @"1,270.10 BTC
706,709.04 USD
508,040.00 EUR
4,381,184.55 CNY
425,238.14 GBP
627,638.19 CHF
785,601.09 CAD
72,442,058.40 JPY
787,357.97 AUD
7,732,676.06 ZAR",
};
(Because what you have in your question is unclear.)
Then you could do this:
var query =
from d in data.Val
.Split(
Environment.NewLine.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries)
select decimal.Parse(
d.Split(' ')[0],
System.Globalization.CultureInfo.GetCultureInfo("en-au"));
decimal[] array = query.ToArray();
That gives you:

Also, you want to parse this as Decimal
, not Double
, as Decimal
is accurate for financial calculations and Double
can lead to rounding errors.
回答2:
This uses a Regex to match blocks of text that start with a digit, contains a comma or period and ends with a digit. Seems to work for me just fine.
You can use double
or Decimal
depending on what you need.
[TestClass]
public class UnitTests
{
[TestMethod]
public void TestMethod1()
{
string str =
@"{ Desc = Marketcap, Val = 1,270.10 BTC 706,709.04 USD 508,040.00 EUR 4,381,184.55 CNY 425,238.14 GBP 627,638.19 CHF 785,601.09 CAD 72,442,058.40 JPY 787,357.97 AUD 7,732,676.06 ZAR }";
MatchCollection matches = Regex.Matches(str, @"\d[\d,\.]+\d");
double[] values = (from Match m in matches select double.Parse(m.Value)).ToArray();
Assert.AreEqual(10,values.Length);
Assert.AreEqual(1270.10,values[0]);
}
}
来源:https://stackoverflow.com/questions/22114029/parsing-all-the-doubles-from-a-string-c-sharp