Sreenath Plakkat
Sreenath Plakkat

Reputation: 1785

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 resultant currency does not contain decimal value. How can I get the exact currency with the decimal part in it?

Upvotes: 4

Views: 941

Answers (1)

harriyott
harriyott

Reputation: 10645

Interesting one this. I ran your code, and the API returned:

{lhs: "1000 Australian dollars",rhs: "1 028.9 U.S. dollars",error: "",icc: true}

There is a space (or possibly Unicode comma-like character) between the 1 and 0 of the rhs result. Looking at your regex, the . is actually matching this character, as . means 'any character' in regex. Matching the actual decimal point needs a backslash. I appended this, and another \d for the numbers after the decimal point. I used the @ syntax to make the escaping easier to read, which gives:

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

This resulted in 1028.9 being returned.

Upvotes: 3

Related Questions