代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何从十进制字符串中去掉零和小数点?

  •  4
  • Edward Tanguay  · 技术社区  · 15 年前

    当前输出的代码如下:

    12.1
    12.100
    12.1000
    12.00
    12
    12.0000
    

    我如何更改它,使其输出:

    12.1
    12.1
    12.1
    12
    12
    12
    

    四舍五入似乎是一回事,但它让我定义了我想要的小数位数,但我希望它们是变量,如上所述。

    如果没有数学方法,我只会去掉字符串右侧的零和小数点,但我认为有一种数学方法可以解决这个问题。

    using System;
    using System.Collections.Generic;
    
    namespace Test8834234
    {
        public class Program
        {
            static void Main(string[] args)
            {
    
                List<string> decimalsAsStrings = new List<string>
                {
                    "12.1",
                    "12.100",
                    "12.1000",
                    "12.00",
                    "12",
                    "12.0000"
                };
    
                foreach (var decimalAsString in decimalsAsStrings)
                {
                    decimal dec = decimal.Parse(decimalAsString);
                    Console.WriteLine(dec);
                }
    
                Console.ReadLine();
    
            }
        }
    }
    
    4 回复  |  直到 8 年前
        1
  •  10
  •   Mark Byers    15 年前

    您还可以将decimal的toString与参数一起使用:

    string s = dec.ToString("0.#");
    

    注意:您的代码可能存在国际化问题。按照您对其进行编码的方式,它将使用来自用户计算机的区域性信息,该计算机可能具有 . 小数点分隔符。这可能会导致程序为具有 . 用于千位分隔符。

    如果要确保parse方法的行为始终相同,可以使用 CultureInfo.InvariantCulture .如果您确实想根据用户的区域性设置来分析字符串,那么您所做的就可以了。

        2
  •  4
  •   Hans Passant    15 年前

    用途:

     Console.WriteLine("{0:0.####}", dec);
    

    了解有关数字格式字符串的详细信息 here...

        3
  •  1
  •   Erwin Mayer    14 年前

    这种字符串格式应该让你的一天成为你的一天:“0。\\\35\\\35\\\35\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\35;”。但请记住,小数最多可以有29个有效数字。

    实例:

    ? (1000000.00000000000050000000000m).ToString("0.#############################")
    -> 1000000.0000000000005
    
    ? (1000000.00000000000050000000001m).ToString("0.#############################")
    -> 1000000.0000000000005
    
    ? (1000000.0000000000005000000001m).ToString("0.#############################")
    -> 1000000.0000000000005000000001
    
    ? (9223372036854775807.0000000001m).ToString("0.#############################")
    -> 9223372036854775807
    
    ? (9223372036854775807.000000001m).ToString("0.#############################")
    -> 9223372036854775807.000000001
    
        4
  •  0
  •   budi TheMrP    8 年前
    public static string RemoveDecimalsFromString(string input)
    {
        decimal IndexOfDot = input.IndexOf(".");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < IndexOfDot; i++)
        {
            sb.Append(input[i]);
        }
    
        return sb.ToString();
    }
    
    推荐文章