简体   繁体   English

如何使尾随零不掉入C#中的十进制数中?

[英]How to make it so trailing zeros are not dropped in a decimal number in C#?

I'm creating a RandomDecimal function that allows you to specify a max value and the precision of the decimal. 我正在创建一个RandomDecimal函数,该函数可让您指定最大值和小数精度。 However, if the last random digit that is chosen happens to be zero, it is dropped and the precision is off. 但是,如果选择的最后一个随机数恰好为零,它将被丢弃并且精度将关闭。 Is it possible to not lose this zero? 是否有可能不失去这个零? I tried converting it to a string then back to a decimal but it's still dropped. 我尝试将其转换为字符串,然后返回至十进制,但仍被删除。

    public static decimal RandomDecimal(int maxValue, int precision)
    {
        decimal result = new Random().Next(maxValue);

        if (maxValue == 0)
        {
            return result;
        }

        int i = 1;

        decimal digit = 0;

        while (i <= precision)
        {
            digit = new Random().Next(10);
            digit = (digit / (Convert.ToDecimal(Math.Pow(10, i))));
            result = result + digit;
            i++;
        }

    //    if (digit == 0)
    //    {
    //     string resultstring = Convert.ToString(result) + '0';
   //      result = Convert.ToDecimal(resultstring);
   //       } This code doesn't do anything because the zero is still dropped.

        return result;
    }

If you want a representation of a number that has not only a value, but knows how many significant digits it has you are better off using something other than double / float / decimal . 如果要表示一个不仅具有值,而且知道多少位数的数字,最好使用double / float / decimal You'll want to create your own type that has both a value and a SignificantDigits property. 您将要创建自己的同时具有值​​和SignificantDigits属性的类型。

You simply want information decimal wasn't designed to have users using. 您只是希望信息decimal不是设计给用户使用的。 In certain situations (where you have no leading/trailing zeros) you coincidentally end up with the same result despite [ decimal ] not knowing the information, but that's irrelevant to you solving your problem. 在某些情况下(没有前导零/尾随零),尽管[ decimal ]不知道该信息,但您还是巧合地得到了相同的结果,但这与您解决问题无关。

What you want can only be done (with built-in types) by returning a string instead of a decimal . 您想要的(只能是内置类型)只能通过返回string而不是decimal You should also declare a Random object once, not creating new ones multiple times within a single method. 您还应该声明一次Random对象,而不是在一个方法中多次创建新对象。

    static Random r = new Random();
    public static string RandomDecimal(int maxValue, int precision)
    {
        decimal result = r.Next(maxValue);

        if (maxValue != 0)
        {
            int i = 1;

            decimal digit = 0;

            while (i <= precision)
            {
                digit = r.Next(10);
                digit = (digit / (Convert.ToDecimal(Math.Pow(10, i))));
                result = result + digit;
                i++;
            }
        }
        var sb = new StringBuilder("0.");
        sb.Append('0', precision);
        return result.ToString(sb.ToString());
    }

The Decimal struct stores a scaling factor internally as a power of 10. According to MSDN , 小数结构在内部将比例因子存储为10的幂。 根据MSDN

The scaling factor also preserves any trailing zeroes in a Decimal number. 比例因子还保留十进制数中的所有尾随零。 Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. 尾随零不会影响算术或比较操作中小数的值。 However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied. 但是,如果应用了适当的格式字符串,则可以通过ToString方法显示尾随零。

It's not obvious to me that there's any way to directly set the scaling factor, except by using the Decimal (Int32, Int32, Int32, Boolean, Byte) constructor, which takes the scaling factor as the last argument. 对我来说,除了使用Decimal (Int32, Int32, Int32, Boolean, Byte)构造函数(将缩放因子作为最后一个参数Decimal (Int32, Int32, Int32, Boolean, Byte)外,没有任何方法可以直接设置缩放因子。 So, in theory, you could create a decimal with significant trailing 0s by creating your Decimals with that constructor. 因此,从理论上讲,您可以通过使用该构造函数创建小数来创建尾随0的小数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM