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)

有帮助吗?

解决方案

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:

Array of Decimals

Also, you want to parse this as Decimal, not Double, as Decimal is accurate for financial calculations and Double can lead to rounding errors.

其他提示

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]);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top