需要根據輸入字符串,生成一個等長的隨機數值,網上查了一下,沒發現比較直接的方法。
自己寫了一個,為便於理解,加了一些中間過程的變量。
雖然可以實現目的,但覺得有些繁瑣,執行效率也不好,故貼於此,請高手指教。
/// <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; } }