是的,XE 提供API但它只是付费的。
制作一个自动化工具来提取数据是not允许。 (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 WebClient())
{
var response = wc.DownloadString(url);
decimal exchangeRate = decimal.Parse(response, CultureInfo.InvariantCulture);
return (amount * exchangeRate).ToString("N3");
}
}
测试代码:
Console.WriteLine($"$ 5 = € {CurrencyConversion(5m, "USD", "EUR")}");
Console.WriteLine($"£ 20 = $ {CurrencyConversion(20m, "GBP", "USD")}");
Result:
$ 5 = € 4,661
£ 20 = $ 25,616
EDIT
使用 NuGet 获取 Newtonsoft.Json
PM> Install-Package Newtonsoft.Json
Code:
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 WebClient())
{
var json = wc.DownloadString(url);
Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(json);
decimal exchangeRate = (decimal)token.SelectToken("rate");
return (amount * exchangeRate).ToString();
}
}