Parse value with Currency symbol

前端 未结 5 1917
耶瑟儿~
耶瑟儿~ 2021-01-21 13:58

I have looked to multiple SO questions on parsing currency, the best (recommended) way seems to be the one I\'m trying below:

var payout = decimal.Parse(\"$2.10\         


        
5条回答
  •  离开以前
    2021-01-21 14:31

    How about a CleanCurrency method?

    /// Loops each char in the string and returns only numbers, . or ,
    static double? CleanCurrency(string currencyStringIn) {
      string temp = "";
      int n;
      for (int i = 0; i < currencyStringIn.Length; i++) {
        string c = currencyStringIn.Substring(i, 1);
        if (int.TryParse(c, out n) || c == "." || c == ",") {
          temp += c;
        }
      }
      if (temp == "") {
        return null;
      else {
        return double.Parse("0" + temp);
      }
    }
    

    The idea here being to just get an actual number regardless of what the string content is.

    double? payout = CleanCurrency("$3.50");
    

提交回复
热议问题