【问题标题】:How can I get the correct currency with 2 decimal places in c#?如何在 c# 中获得小数点后 2 位的正确货币?
【发布时间】:2026-02-23 02:35:01
【问题描述】:
 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");
           }

       }

在这种情况下,生成的货币不包含十进制值。如何获得包含小数部分的确切货币?

【问题讨论】:

    标签: regex currency


    【解决方案1】:

    这很有趣。我运行了您的代码,API 返回:

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

    在 rhs 结果的 1 和 0 之间有一个空格(或者可能是类似 Unicode 逗号的字符)。查看您的正则表达式,.实际上是匹配这个字符,如 .在正则表达式中表示“任何字符”。匹配实际小数点需要一个反斜杠。我附加了这个,另一个 \d 用于小数点后的数字。我使用 @ 语法使转义更容易阅读,这给出了:

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

    这导致返回 1028.9。

    【讨论】:

    • 非常感谢,我对其稍作改动 Regex regex = new Regex(@"rhs: \""(\d*.\d*\.?\d*)");
    • 啊,是的;我的有一个强制性的小数点,只有一位小数。