How can I get the correct currency with 2 decimal places in C #?

public PriceTable ConvertToUSDollar(decimal Amount,string Currency) { try { var toCurrency = "USD"; var fromCurrency = "AUD"; string url = string.Format("http://www.google.com/ig/calculator?hl=en&q= {2}{0}%3D%3F{1}", fromCurrency .ToUpper(), toCurrency.ToUpper(), 1000); WebClient web = new WebClient(); string response = web.DownloadString(url); Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)"); Match match = regex.Match(response); string rate = (match.Groups[1].Value.Trim()); rate = Regex.Replace(rate, @"\s", ""); decimal Value = Convert.ToDecimal(rate); var pricetable = new PriceTable() { Price = Value }; return pricetable; } catch(Exception e) { throw new Exception("Error Occoured While Converting"); } } 

In this case, the resulting currency does not contain a decimal value. How can I get the exact currency with a decimal in it?

+4
source share
1 answer

I wonder what that is. I ran your code and the API returned:

 {lhs: "1000 Australian dollars",rhs: "1 028.9 US dollars",error: "",icc: true} 

There is a space between 1 and 0 of the rhs result (or, possibly, a Unicode character). Looking at your regular expression. actually matches that symbol like. means "any character" in regular expression. Matching the actual decimal point requires a backslash. I added this and the other is \ d for numbers after the decimal point. I used the @ syntax to make reading easier, which gives:

 Regex regex = new Regex(@"rhs: \""(\d*.\d*\.\d)"); 

This led to a return of 1,028.9.

+3
source

Source: https://habr.com/ru/post/1379992/


All Articles