【问题标题】:How to convert decimal into integer in a sentence of character in C#?如何在C#中的一个字符的句子中将十进制转换为整数?
【发布时间】:2020-03-04 09:48:33
【问题描述】:

示例:*

string str = "i have rs 12.55"

我想把它打印成

"i have rs 12"

忽略 .55 在句子中。

【问题讨论】:

  • 发布您尝试过的内容
  • 所以您希望“我有 12.99999 卢比”显示为“我有 12 卢比”?不是“我有 13 卢比”?
  • 那个重复的不是重复的......它对于解析字符串更困难的部分真的没有帮助。

标签: c# string integer


【解决方案1】:

您可以尝试使用字符串函数Substring 并捕获字符串直到.

string str = "i have rs 12.55";
var result = str.Substring(0, str.IndexOf('.'));

但是,我建议在形成字符串之前从12.55 中删除小数部分。

double value = 12.55;
string str = $"i have rs {(int)value}";

decimal value = 12.55M;
string str = $"i have rs {decimal.Truncate(value)}";

【讨论】:

    【解决方案2】:

    为了去除所有小数部分,你可以试试正则表达式

    using System.Text.RegularExpressions;
    
    ... 
    
    Regex regex = new Regex(@"(?<=[0-9]+)\.[0-9]+");
    
    string result = regex.Replace(str, "");
    

    演示:

      string[] tests = new string[] {
        "i have rs 12.55",
        "I have rs 12.55 and -8.63 but 0.78963",
        "list : A.B.C.D",
        "12 - 45... but 78.99"
      };
    
      Regex regex = new Regex(@"(?<=[0-9]+)\.[0-9]+");
    
      string report = string.Join(Environment.NewLine, tests
        .Select(test => $"{test,-40} => {regex.Replace(test, "")}")) ;
    
      Console.Write(report);
    

    结果:

    i have rs 12.55                          => i have rs 12
    I have rs 12.55 and -8.63 but 0.78963    => I have rs 12 and -8 but 0
    list : A.B.C.D                           => list : A.B.C.D
    12 - 45... but 78.99                     => 12 - 45... but 78
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2018-07-07
      • 2021-03-04
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多