【问题标题】:How to use String.Format to show only cents and omit dollars如何使用 String.Format 仅显示美分并省略美元
【发布时间】:2014-10-24 17:58:31
【问题描述】:

我只想显示小数点的十分之一。

decimal d = 44.22m;

var s = d.ToString("");

如何使s == "22" 为真?

PS:我很清楚我可以做一些数学运算,但我想只使用 Binding 和 StringFormat 在 WPF 中显示十分之一

【问题讨论】:

  • 用转换器可以吗?
  • 我真的不想让事情复杂化,但如果没有可用的 StringFormat,我会使用转换器
  • 我认为您不会得到不需要使用数学而只需要String.FormatToString 的答案。顺便说一句,如果你使用像 “如何使用 String.Format 只显示美分并省略美元”这样的标题,这个问题会更容易理解。
  • 同意,使用转换器
  • @TimSchmelter:我也不认为有纯粹的 -String.Format- 方式来获得美分。

标签: c# wpf decimal


【解决方案1】:

这不是最好的,但它有效:

        decimal d = 44.22m;
        string ds = d.ToString().Remove(0, (d.ToString().IndexOf(',') + 1));

【讨论】:

    【解决方案2】:
    decimal d = 44.22m;
    
    Regex regex = new Regex(@"\d*(?=m)");
    Match match = regex.Match(d);
    if (match.Success)
    {
            Console.WriteLine(match.Value);
    }
    

    【讨论】:

      【解决方案3】:

      如果你需要大量的操作,也许为这一步设置一个功能!?我猜只使用String.Format 是行不通的。

      int getDecimals (decimal d)
      {
          try
          {
              int s = Convert.ToInt32(string.Format("{0}", d.ToString().Split('.')[1]));
              return s;
          }
          catch { //whatever u want// }
      }
      
      // ==> //
      
      decimal d = 44.22m;
      
      string s = getDecimals(d).ToString();
      

      【讨论】:

        【解决方案4】:

        这里有一个类似问题的答案。

        https://stackoverflow.com/a/19374418/4101237

        用户发布 https://stackoverflow.com/users/2608383/karthik-krishna-baiju

        原邮编:

        string outPut = "0";
        if (MyValue.ToString().Split('.').Length == 2)
        {
        outPut = MyValue.ToString().Split('.')[1].Substring(0, MyValue.ToString().Split('.')[1].Length);
        }
        Console.WriteLine(outPut);
        

        根据您的要求修改:

        decimal d = 44.22m;
        string outPut = "0";
        if (d.ToString().Split('.').Length == 2)
        {
            outPut = d.ToString().Split('.')[1].Substring(0, d.ToString().Split('.')[1].Length);
        }
        Console.WriteLine(outPut);
        

        --输入样本--
        1) 46.0
        2) 46.01
        3) 46.000001
        4) 46.1 5) 46.12
        6) 46.123
        7) 46.1234

        --输出--
        1) 0
        2) 01
        3) 000001
        4) 1
        5) 12
        6) 123
        7) 1234

        【讨论】:

          猜你喜欢
          • 2021-03-31
          • 1970-01-01
          • 2019-09-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多