年过半百的老李头

知足、感恩、平常心

导航

生成等长随机数值的方法

需要根据输入字符串,生成一个等长的随机数值,网上查了一下,没发现比较直接的方法。

自己写了一个,为便于理解,加了一些中间过程的变量。

虽然可以实现目的,但觉得有些繁琐,执行效率也不好,故贴于此,请高手指教。

 

       /// <summary>
        /// 数值字符串转换成等长的随机数
        /// </summary>
        /// <param name="inputStr">输入字符串</param>
        /// <returns></returns>
        private static string StringConvertRandomDouble(string inputStr)
        {
            if (inputStr.Length > 17)
            {
                return inputStr;//Double类型超出17位长度,需用科学计数法表示。转换会抛出异常。
            }
            string top = "";
            int inputStrLenght;//输入字符串原始长度
            if (double.TryParse(inputStr, out double newDouble))//判断能否转换位double类型
            {
                int IntegerLength;//整数部分长度
                double tempDouble = Math.Floor(newDouble);//向下取整,可能有符号,下面判断处理
                if (tempDouble < 0)
                {
                    IntegerLength = tempDouble.ToString().Length - 1;
                    top = "-";
                    inputStrLenght = inputStr.Length - 1;
                }
                else
                {
                    IntegerLength = tempDouble.ToString().Length;
                    inputStrLenght = inputStr.Length;
                }
                string a = "1".PadRight(IntegerLength, '0');//得到等长 100
                string b = "9".PadLeft(IntegerLength, '9');//得到等长的 999
                double minDouble = Convert.ToDouble(a);
                double maxDouble = Convert.ToDouble(b);
                Random _random = new Random();
                double outputDouble;
                if (_random != null)
                {
                    //在指定的范围内取随机的 Double
                    outputDouble = _random.NextDouble() * (maxDouble - minDouble) + minDouble;
                }
                else
                {
                    outputDouble = 0.0d;
                }
                return top + outputDouble.ToString().Substring(0, inputStrLenght);
            }
            else
            {
                return inputStr;
            }
        }

 

posted on 2021-12-12 02:43  李运琪  阅读(178)  评论(0编辑  收藏  举报