C#从XE获取当前汇率

我需要在我的应用程序上显示当前汇率。是否可以从http://www.xe.com(XE 转换器)中检索汇率在这里我尝试了什么:


我需要在我的应用程序上显示当前汇率。
是否可以从http://www.xe.com(XE 转换器)中检索汇率
在这里我尝试了什么:

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
        {
            string Output = "";
             string fromCurrency1 = comboBox1.Text;
             string toCurrency1 = comboBox2.Text;
             decimal amount1 = Convert.ToDecimal(textBox1.Text);
            // For other currency symbols see http://finance.yahoo.com/currency-converter/
            // Construct URL to query the Yahoo! Finance API
            const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
            string url = string.Format(urlPattern, fromCurrency1, toCurrency1);
            // Get response as string
            string response = new Web().DownloadString(url);
            // Convert string to number
            decimal exchangeRate =
                decimal.P(response, System.Globalization.CultureInfo.InvariantCulture);
            // Output the result
            Output = (amount1 * exchangeRate).ToString();
            textBox2.Text = Output;
            return Output;
        }

有了这个代码,我没有完整的输出...小数部分不是
显示...

3

是的,XE 提供API,但它是付费的。不允许使用自动工具提取数据。(source)

我试过你的代码,它为我工作。你到底是什么意思the decimal part is not showing

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
    string url = string.Format(urlPattern, fromCurrency, toCurrency);
    using (var wc = new Web())
    {
        var response = wc.DownloadString(url);
        decimal exchangeRate = decimal.P(response, CultureInfo.InvariantCulture);
        return (amount * exchangeRate).ToString("N3");
    }
}

测试代码:

Console.WriteLine($"$ 5 = € {CurrencyConversion(5m, "USD", "EUR")}");
Console.WriteLine($"£ 20 = $ {CurrencyConversion(20m, "GBP", "USD")}");

结果:

$ 5 = € 4,661
£ 20 = $ 25,616
EDIT

使用 NuGet 获取 Newtonsoft.Json

PM> Install-Package Newtonsoft.Json

代码:

private const string urlPattern = "http://rate-exchange-1.appspot.com/currency?from={0}&to={1}";
    public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
    {
        string url = string.Format(urlPattern, fromCurrency, toCurrency);
        using (var wc = new Web())
        {
            var json = wc.DownloadString(url);
            Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.P(json);
            decimal exchangeRate = (decimal)token.SelectToken("rate");
            return (amount * exchangeRate).ToString();
        }
    }

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(430)
请求 utl_http包时 Oracle错误“ORA-28759:无法打开文件”
上一篇
在给定范围内查找函数的根(root of the function)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(31条)