简体   繁体   English

没有科学记数法的双精度字符串转换

[英]Double to string conversion without scientific notation

How to convert a double into a floating-point string representation without scientific notation in the .NET Framework?如何在 .NET Framework 中将 double 转换为没有科学记数法的浮点字符串表示形式?

"Small" samples (effective numbers may be of any size, such as 1.5E200 or 1e-200 ) : “小”样本(有效数字可以是任何大小,例如1.5E2001e-200 ):

3248971234698200000000000000000000000000000000
0.00000000000000000000000000000000000023897356978234562

None of the standard number formats are like this, and a custom format also doesn't seem to allow having an open number of digits after the decimal separator.没有一个标准数字格式是这样的,自定义格式似乎也不允许在小数点分隔符后有一个开放的位数。

This is not a duplicate of How to convert double to string without the power to 10 representation (E-05) because the answers given there do not solve the issue at hand.这不是How to convert double to string without the power to 10 representation (E-05)的副本,因为那里给出的答案并不能解决手头的问题。 The accepted solution in this question was to use a fixed point (such as 20 digits), which is not what I want.这个问题中公认的解决方案是使用一个固定点(例如 20 位),这不是我想要的。 A fixed point formatting and trimming the redundant 0 doesn't solve the issue either because the max width for fixed width is 99 characters.定点格式化和修剪多余的 0 也不能解决问题,因为固定宽度的最大宽度是 99 个字符。

Note: the solution has to deal correctly with custom number formats (eg other decimal separator, depending on culture information).注意:解决方案必须正确处理自定义数字格式(例如,其他小数分隔符,取决于文化信息)。

Edit: The question is really only about displaing aforementioned numbers.编辑:这个问题实际上只是关于取代上述数字。 I'm aware of how floating point numbers work and what numbers can be used and computed with them.我知道浮点数是如何工作的,以及可以使用和计算哪些数字。

For a general-purpose¹ solution you need to preserve 339 places:对于通用¹解决方案,您需要保留 339 个位置:

doubleValue.ToString("0." + new string('#', 339))

The maximum number of non-zero decimal digits is 16. 15 are on the right side of the decimal point.非零小数位数的最大数量为 16。15 在小数点右侧。 The exponent can move those 15 digits a maximum of 324 places to the right.指数最多可以将这 15 位数字向右移动 324 位。 ( See the range and precision. ) 见范围和精度。

It works for double.Epsilon , double.MinValue , double.MaxValue , and anything in between.它适用于double.Epsilondouble.MinValuedouble.MaxValue以及介于两者之间的任何内容。

The performance will be much greater than the regex/string manipulation solutions since all formatting and string work is done in one pass by unmanaged CLR code.性能将比正则表达式/字符串操作解决方案高得多,因为所有格式化和字符串工作都是由非托管 CLR 代码一次性完成的。 Also, the code is much simpler to prove correct.此外,代码更容易证明是正确的。

For ease of use and even better performance, make it a constant:为了易于使用和更好的性能,将其设为常数:

public static class FormatStrings
{
    public const string DoubleFixedPoint = "0.###################################################################################################################################################################################################################################################################################################################################################";
}

¹ Update: I mistakenly said that this was also a lossless solution. ¹更新:我错误地说这也是一个无损解决方案。 In fact it is not, since ToString does its normal display rounding for all formats except r .事实上并非如此,因为ToString对除r之外的所有格式进行正常显示舍入。 Live example. 活生生的例子。 Thanks, @Loathing!谢谢,@Loathing! Please see Lothing's answer if you need the ability to roundtrip in fixed point notation (ie, if you're using .ToString("r") today).如果您需要以定点表示法往返的能力(即,如果您今天使用.ToString("r") ),请参阅Lothing 的答案

I had a similar problem and this worked for me:我有一个类似的问题,这对我有用:

doubleValue.ToString("F99").TrimEnd('0')

F99 may be overkill, but you get the idea. F99 可能是矫枉过正,但你明白了。

This is a string parsing solution where the source number (double) is converted into a string and parsed into its constituent components.这是一个字符串解析解决方案,将源数字(双精度)转换为字符串并解析为其组成部分。 It is then reassembled by rules into the full-length numeric representation.然后通过规则将其重新组合成全长数字表示。 It also accounts for locale as requested.它还根据要求考虑语言环境。

Update : The tests of the conversions only include single-digit whole numbers, which is the norm, but the algorithm also works for something like: 239483.340901e-20更新:转换测试仅包括一位整数,这是常态,但该算法也适用于:239483.340901e-20

using System;
using System.Text;
using System.Globalization;
using System.Threading;

public class MyClass
{
    public static void Main()
    {
        Console.WriteLine(ToLongString(1.23e-2));            
        Console.WriteLine(ToLongString(1.234e-5));           // 0.00010234
        Console.WriteLine(ToLongString(1.2345E-10));         // 0.00000001002345
        Console.WriteLine(ToLongString(1.23456E-20));        // 0.00000000000000000100023456
        Console.WriteLine(ToLongString(5E-20));
        Console.WriteLine("");
        Console.WriteLine(ToLongString(1.23E+2));            // 123
        Console.WriteLine(ToLongString(1.234e5));            // 1023400
        Console.WriteLine(ToLongString(1.2345E10));          // 1002345000000
        Console.WriteLine(ToLongString(-7.576E-05));         // -0.00007576
        Console.WriteLine(ToLongString(1.23456e20));
        Console.WriteLine(ToLongString(5e+20));
        Console.WriteLine("");
        Console.WriteLine(ToLongString(9.1093822E-31));        // mass of an electron
        Console.WriteLine(ToLongString(5.9736e24));            // mass of the earth 

        Console.ReadLine();
    }

    private static string ToLongString(double input)
    {
        string strOrig = input.ToString();
        string str = strOrig.ToUpper();

        // if string representation was collapsed from scientific notation, just return it:
        if (!str.Contains("E")) return strOrig;

        bool negativeNumber = false;

        if (str[0] == '-')
        {
            str = str.Remove(0, 1);
            negativeNumber = true;
        }

        string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        char decSeparator = sep.ToCharArray()[0];

        string[] exponentParts = str.Split('E');
        string[] decimalParts = exponentParts[0].Split(decSeparator);

        // fix missing decimal point:
        if (decimalParts.Length==1) decimalParts = new string[]{exponentParts[0],"0"};

        int exponentValue = int.Parse(exponentParts[1]);

        string newNumber = decimalParts[0] + decimalParts[1];

        string result;

        if (exponentValue > 0)
        {
            result = 
                newNumber + 
                GetZeros(exponentValue - decimalParts[1].Length);
        }
        else // negative exponent
        {
            result = 
                "0" + 
                decSeparator + 
                GetZeros(exponentValue + decimalParts[0].Length) + 
                newNumber;

            result = result.TrimEnd('0');
        }

        if (negativeNumber)
            result = "-" + result;

        return result;
    }

    private static string GetZeros(int zeroCount)
    {
        if (zeroCount < 0) 
            zeroCount = Math.Abs(zeroCount);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < zeroCount; i++) sb.Append("0");    

        return sb.ToString();
    }
}

You could cast the double to decimal and then do ToString() .您可以将double精度转换为decimal ,然后执行ToString()

(0.000000005).ToString()   // 5E-09
((decimal)(0.000000005)).ToString()   // 0,000000005

I haven't done performance testing which is faster, casting from 64-bit double to 128-bit decimal or a format string of over 300 chars.我还没有进行更快的性能测试,将 64 位double转换为 128 位decimal或超过 300 个字符的格式字符串。 Oh, and there might possibly be overflow errors during conversion, but if your values fit a decimal this should work fine.哦,在转换过程中可能会出现溢出错误,但如果你的值适合decimal ,这应该可以正常工作。

Update: The casting seems to be a lot faster.更新:铸造似乎要快得多。 Using a prepared format string as given in the other answer, formatting a million times takes 2.3 seconds and casting only 0.19 seconds.使用另一个答案中给出的准备好的格式字符串,格式化一百万次需要 2.3 秒,并且只需要 0.19 秒。 Repeatable.可重复。 That's 10x faster .这快了10 倍 Now it's only about the value range.现在它只是关于价值范围。

This is what I've got so far, seems to work, but maybe someone has a better solution:这是我到目前为止所得到的,似乎有效,但也许有人有更好的解决方案:

private static readonly Regex rxScientific = new Regex(@"^(?<sign>-?)(?<head>\d+)(\.(?<tail>\d*?)0*)?E(?<exponent>[+\-]\d+)$", RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture|RegexOptions.CultureInvariant);

public static string ToFloatingPointString(double value) {
    return ToFloatingPointString(value, NumberFormatInfo.CurrentInfo);
}

public static string ToFloatingPointString(double value, NumberFormatInfo formatInfo) {
    string result = value.ToString("r", NumberFormatInfo.InvariantInfo);
    Match match = rxScientific.Match(result);
    if (match.Success) {
        Debug.WriteLine("Found scientific format: {0} => [{1}] [{2}] [{3}] [{4}]", result, match.Groups["sign"], match.Groups["head"], match.Groups["tail"], match.Groups["exponent"]);
        int exponent = int.Parse(match.Groups["exponent"].Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
        StringBuilder builder = new StringBuilder(result.Length+Math.Abs(exponent));
        builder.Append(match.Groups["sign"].Value);
        if (exponent >= 0) {
            builder.Append(match.Groups["head"].Value);
            string tail = match.Groups["tail"].Value;
            if (exponent < tail.Length) {
                builder.Append(tail, 0, exponent);
                builder.Append(formatInfo.NumberDecimalSeparator);
                builder.Append(tail, exponent, tail.Length-exponent);
            } else {
                builder.Append(tail);
                builder.Append('0', exponent-tail.Length);
            }
        } else {
            builder.Append('0');
            builder.Append(formatInfo.NumberDecimalSeparator);
            builder.Append('0', (-exponent)-1);
            builder.Append(match.Groups["head"].Value);
            builder.Append(match.Groups["tail"].Value);
        }
        result = builder.ToString();
    }
    return result;
}

// test code
double x = 1.0;
for (int i = 0; i < 200; i++) {
    x /= 10;
}
Console.WriteLine(x);
Console.WriteLine(ToFloatingPointString(x));

The problem using #.###...### or F99 is that it doesn't preserve precision at the ending decimal places, eg:使用#.###...###F99的问题是它不保留小数点末尾的精度,例如:

String t1 = (0.0001/7).ToString("0." + new string('#', 339)); // 0.0000142857142857143
String t2 = (0.0001/7).ToString("r");                         //      1.4285714285714287E-05

The problem with DecimalConverter.cs is that it is slow. DecimalConverter.cs的问题在于它很慢。 This code is the same idea as Sasik's answer, but twice as fast.此代码与 Sasik 的答案相同,但速度是后者的两倍。 Unit test method at bottom.单元测试方法在底部。

public static class RoundTrip {

    private static String[] zeros = new String[1000];

    static RoundTrip() {
        for (int i = 0; i < zeros.Length; i++) {
            zeros[i] = new String('0', i);
        }
    }

    private static String ToRoundTrip(double value) {
        String str = value.ToString("r");
        int x = str.IndexOf('E');
        if (x < 0) return str;

        int x1 = x + 1;
        String exp = str.Substring(x1, str.Length - x1);
        int e = int.Parse(exp);

        String s = null;
        int numDecimals = 0;
        if (value < 0) {
            int len = x - 3;
            if (e >= 0) {
                if (len > 0) {
                    s = str.Substring(0, 2) + str.Substring(3, len);
                    numDecimals = len;
                }
                else
                    s = str.Substring(0, 2);
            }
            else {
                // remove the leading minus sign
                if (len > 0) {
                    s = str.Substring(1, 1) + str.Substring(3, len);
                    numDecimals = len;
                }
                else
                    s = str.Substring(1, 1);
            }
        }
        else {
            int len = x - 2;
            if (len > 0) {
                s = str[0] + str.Substring(2, len);
                numDecimals = len;
            }
            else
                s = str[0].ToString();
        }

        if (e >= 0) {
            e = e - numDecimals;
            String z = (e < zeros.Length ? zeros[e] : new String('0', e));
            s = s + z;
        }
        else {
            e = (-e - 1);
            String z = (e < zeros.Length ? zeros[e] : new String('0', e));
            if (value < 0)
                s = "-0." + z + s;
            else
                s = "0." + z + s;
        }

        return s;
    }

    private static void RoundTripUnitTest() {
        StringBuilder sb33 = new StringBuilder();
        double[] values = new [] { 123450000000000000.0, 1.0 / 7, 10000000000.0/7, 100000000000000000.0/7, 0.001/7, 0.0001/7, 100000000000000000.0, 0.00000000001,
         1.23e-2, 1.234e-5, 1.2345E-10, 1.23456E-20, 5E-20, 1.23E+2, 1.234e5, 1.2345E10, -7.576E-05, 1.23456e20, 5e+20, 9.1093822E-31, 5.9736e24, double.Epsilon };

        foreach (int sign in new [] { 1, -1 }) {
            foreach (double val in values) {
                double val2 = sign * val;
                String s1 = val2.ToString("r");
                String s2 = ToRoundTrip(val2);

                double val2_ = double.Parse(s2);
                double diff = Math.Abs(val2 - val2_);
                if (diff != 0) {
                    throw new Exception("Value {0} did not pass ToRoundTrip.".Format2(val.ToString("r")));
                }
                sb33.AppendLine(s1);
                sb33.AppendLine(s2);
                sb33.AppendLine();
            }
        }
    }
}

In the old days when we had to write our own formatters, we'd isolate the mantissa and exponent and format them separately.在过去,当我们不得不编写自己的格式化程序时,我们会隔离尾数和指数并分别格式化它们。

In this article by Jon Skeet ( https://csharpindepth.com/articles/FloatingPoint ) he provides a link to his DoubleConverter.cs routine that should do exactly what you want.在 Jon Skeet 的这篇文章 ( https://csharpindepth.com/articles/FloatingPoint ) 中,他提供了一个指向他的 DoubleConverter.cs 例程的链接,该例程应该完全符合您的要求。 Skeet also refers to this at extracting mantissa and exponent from double in c# . Skeet 在从 c# 中的 double 中提取尾数和指数时也提到了这一点。

The obligatory Logarithm-based solution.强制性的基于对数的解决方案。 Note that this solution, because it involves doing math, may reduce the accuracy of your number a little bit.请注意,此解决方案由于涉及数学运算,可能会稍微降低您的数字的准确性。 Not heavily tested.没有经过严格测试。

private static string DoubleToLongString(double x)
{
    int shift = (int)Math.Log10(x);
    if (Math.Abs(shift) <= 2)
    {
        return x.ToString();
    }

    if (shift < 0)
    {
        double y = x * Math.Pow(10, -shift);
        return "0.".PadRight(-shift + 2, '0') + y.ToString().Substring(2);
    }
    else
    {
        double y = x * Math.Pow(10, 2 - shift);
        return y + "".PadRight(shift - 2, '0');
    }
}

Edit: If the decimal point crosses non-zero part of the number, this algorithm will fail miserably.编辑:如果小数点越过数字的非零部分,该算法将惨遭失败。 I tried for simple and went too far.我尝试简单但走得太远了。

I have just improvised on the code above to make it work for negative exponential values.我刚刚对上面的代码进行了即兴创作,使其适用于负指数值。

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;

namespace ConvertNumbersInScientificNotationToPlainNumbers
{
    class Program
    {
        private static string ToLongString(double input)
        {
            string str = input.ToString(System.Globalization.CultureInfo.InvariantCulture);

            // if string representation was collapsed from scientific notation, just return it:
            if (!str.Contains("E")) return str;

            var positive = true;
            if (input < 0)
            {
                positive = false;
            }

            string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            char decSeparator = sep.ToCharArray()[0];

            string[] exponentParts = str.Split('E');
            string[] decimalParts = exponentParts[0].Split(decSeparator);

            // fix missing decimal point:
            if (decimalParts.Length == 1) decimalParts = new string[] { exponentParts[0], "0" };

            int exponentValue = int.Parse(exponentParts[1]);

            string newNumber = decimalParts[0].Replace("-", "").
                Replace("+", "") + decimalParts[1];

            string result;

            if (exponentValue > 0)
            {
                if (positive)
                    result =
                        newNumber +
                        GetZeros(exponentValue - decimalParts[1].Length);
                else

                    result = "-" +
                     newNumber +
                     GetZeros(exponentValue - decimalParts[1].Length);


            }
            else // negative exponent
            {
                if (positive)
                    result =
                        "0" +
                        decSeparator +
                        GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                                   Replace("+", "").Length) + newNumber;
                else
                    result =
                    "-0" +
                    decSeparator +
                    GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                             Replace("+", "").Length) + newNumber;

                result = result.TrimEnd('0');
            }
            float temp = 0.00F;

            if (float.TryParse(result, out temp))
            {
                return result;
            }
            throw new Exception();
        }

        private static string GetZeros(int zeroCount)
        {
            if (zeroCount < 0)
                zeroCount = Math.Abs(zeroCount);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < zeroCount; i++) sb.Append("0");

            return sb.ToString();
        }

        public static void Main(string[] args)
        {
            //Get Input Directory.
            Console.WriteLine(@"Enter the Input Directory");
            var readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the input path properly.");
                return;
            }
            var pathToInputDirectory = readLine.Trim();

            //Get Output Directory.
            Console.WriteLine(@"Enter the Output Directory");
            readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the output path properly.");
                return;
            }
            var pathToOutputDirectory = readLine.Trim();

            //Get Delimiter.
            Console.WriteLine("Enter the delimiter;");
            var columnDelimiter = (char)Console.Read();

            //Loop over all files in the directory.
            foreach (var inputFileName in Directory.GetFiles(pathToInputDirectory))
            {
                var outputFileWithouthNumbersInScientificNotation = string.Empty;
                Console.WriteLine("Started operation on File : " + inputFileName);

                if (File.Exists(inputFileName))
                {
                    // Read the file
                    using (var file = new StreamReader(inputFileName))
                    {
                        string line;
                        while ((line = file.ReadLine()) != null)
                        {
                            String[] columns = line.Split(columnDelimiter);
                            var duplicateLine = string.Empty;
                            int lengthOfColumns = columns.Length;
                            int counter = 1;
                            foreach (var column in columns)
                            {
                                var columnDuplicate = column;
                                try
                                {
                                    if (Regex.IsMatch(columnDuplicate.Trim(),
                                                      @"^[+-]?[0-9]+(\.[0-9]+)?[E]([+-]?[0-9]+)$",
                                                      RegexOptions.IgnoreCase))
                                    {
                                        Console.WriteLine("Regular expression matched for this :" + column);

                                        columnDuplicate = ToLongString(Double.Parse
                                                                           (column,
                                                                            System.Globalization.NumberStyles.Float));

                                        Console.WriteLine("Converted this no in scientific notation " +
                                                          "" + column + "  to this number " +
                                                          columnDuplicate);
                                    }
                                }
                                catch (Exception)
                                {

                                }
                                duplicateLine = duplicateLine + columnDuplicate;

                                if (counter != lengthOfColumns)
                                {
                                    duplicateLine = duplicateLine + columnDelimiter.ToString();
                                }
                                counter++;
                            }
                            duplicateLine = duplicateLine + Environment.NewLine;
                            outputFileWithouthNumbersInScientificNotation = outputFileWithouthNumbersInScientificNotation + duplicateLine;
                        }

                        file.Close();
                    }

                    var outputFilePathWithoutNumbersInScientificNotation
                        = Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));

                    //Create Directory If it does not exist.
                    if (!Directory.Exists(pathToOutputDirectory))
                        Directory.CreateDirectory(pathToOutputDirectory);

                    using (var outputFile =
                        new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
                    {
                        outputFile.Write(outputFileWithouthNumbersInScientificNotation);
                        outputFile.Close();
                    }

                    Console.WriteLine("The transformed file is here :" +
                        outputFilePathWithoutNumbersInScientificNotation);
                }
            }
        }
    }
}

This code takes an input directory and based on the delimiter converts all values in scientific notation to numeric format.此代码采用输入目录并基于分隔符将科学计数法中的所有值转换为数字格式。

Thanks谢谢

try this one:试试这个:

public static string DoubleToFullString(double value, 
                                        NumberFormatInfo formatInfo)
{
    string[] valueExpSplit;
    string result, decimalSeparator;
    int indexOfDecimalSeparator, exp;

    valueExpSplit = value.ToString("r", formatInfo)
                         .ToUpper()
                         .Split(new char[] { 'E' });

    if (valueExpSplit.Length > 1)
    {
        result = valueExpSplit[0];
        exp = int.Parse(valueExpSplit[1]);
        decimalSeparator = formatInfo.NumberDecimalSeparator;

        if ((indexOfDecimalSeparator 
             = valueExpSplit[0].IndexOf(decimalSeparator)) > -1)
        {
            exp -= (result.Length - indexOfDecimalSeparator - 1);
            result = result.Replace(decimalSeparator, "");
        }

        if (exp >= 0) result += new string('0', Math.Abs(exp));
        else
        {
            exp = Math.Abs(exp);
            if (exp >= result.Length)
            {
                result = "0." + new string('0', exp - result.Length) 
                             + result;
            }
            else
            {
                result = result.Insert(result.Length - exp, decimalSeparator);
            }
        }
    }
    else result = valueExpSplit[0];

    return result;
}

Being millions of programmers world wide, it's always a good practice to try search if someone has bumped into your problem already.作为全世界数以百万计的程序员,尝试搜索是否有人已经遇到了您的问题总是一个好习惯。 Sometimes there's solutions are garbage, which means it's time to write your own, and sometimes there are great, such as the following:有时有解决方案是垃圾,这意味着是时候自己编写了,有时也有很棒的,例如以下:

http://www.yoda.arachsys.com/csharp/DoubleConverter.cs http://www.yoda.arachsys.com/csharp/DoubleConverter.cs

(details: http://www.yoda.arachsys.com/csharp/floatingpoint.html ) (详情: http ://www.yoda.arachsys.com/csharp/floatingpoint.html)

string strdScaleFactor = dScaleFactor.ToString(); // where dScaleFactor = 3.531467E-05

decimal decimalScaleFactor = Decimal.Parse(strdScaleFactor, System.Globalization.NumberStyles.Float);

I don't know if my answer to the question can still be helpful.我不知道我对这个问题的回答是否仍然有用。 But in this case I suggest the "decomposition of the double variable into decimal places" to store it in an Array / Array of data of type String.但在这种情况下,我建议“将双变量分解为小数位”以将其存储在字符串类型的数据数组/数组中。

This process of decomposition and storage in parts (number by number) from double to string, would basically work with the use of two loops and an "alternative" (if you thought of workaround, I think you got it), where the first loop will extract the values from double without converting to String, resulting in blessed scientific notation and storing number by number in an Array.这种从双精度到字符串的分解和存储部分(逐个数字)的过程基本上可以使用两个循环和一个“替代方案”(如果你想到解决方法,我想你明白了),其中第一个循环将从 double 中提取值而不转换为 String,从而产生有福的科学记数法并将数字按数字存储在数组中。 And this will be done using MOD - the same method to check a palindrome number, which would be for example:这将使用MOD完成 - 检查回文数的相同方法,例如:

String[] Array_ = new double[ **here you will put an extreme value of places your DOUBLE can reach, you must have a prediction**];

for (int i = 0, variableDoubleMonstrous > 0, i++){
x = variableDoubleMonstrous %10;
Array_[i] = x;
variableDoubleMonstrous /= 10;
}

And the second loop to invert the Array values ​​(because in this process of checking a palindrome, the values ​​invert from the last place, to the first, from the penultimate to the second and so on. Remember?) to get the original value:而第二个循环将Array的值倒置(因为在这个检查回文的过程中,值从最后一位倒置到第一位,从倒数第二位倒置到第二位等等。还记得吗?)得到原始值:

String[] ArrayFinal = new String[the same number of "places" / indices of the other Array / Data array];

int lengthArray = Array_.Length;

for (int i = 0, i < Array_.Length, i++){
    FinalArray[i] = Array_[lengthArray - 1];
    lengthArray--;
    }

***Warning: There's a catch that I didn't pay attention to. ***警告:有一个我没有注意的问题。 In that case there will be no "."在这种情况下,将没有“。” (floating point decimal separator or double), so this solution is not generalized. (浮点小数分隔符或双精度),所以这个解决方案没有推广。 But if it is really important to use decimal separators, unfortunately the only possibility (If done well, it will have a great performance) is: **Use a routine to get the position of the decimal point of the original value, the one with scientific notation - the important thing is that you know that this floating point is before a number such as the "Length" position x, and after a number such as the y position - extracting each digit using the loops - as shown above - and at the end "export" the data from the last Array to another one, including the decimal place divider (the comma, or the period , if variable decimal, double or float) in the imaginary position that was in the original variable, in the "real" position of that matrix.但是如果使用小数分隔符真的很重要,不幸的是唯一的可能性(如果做得好,它将有很好的性能)是:**使用例程获取原始值的小数点位置,与科学记数法 - 重要的是你知道这个浮点在诸如“长度”位置 x 之类的数字之前,在诸如 y 位置之类的数字之后 - 使用循环提取每个数字 - 如上所示 - 并且在最后将数据从最后一个数组“导出”到另一个数组,包括原始变量中的假想位置中的小数位分隔符(逗号或句点,如果变量为十进制、双精度或浮点数),在“该矩阵的真实”位置。

*** The concept of position is, find out how many numbers occur before the decimal point, so with this information you will be able to store in the String Array the point in the real position. *** 位置的概念是,找出小数点前有多少个数字,因此有了这些信息,您就可以将点的实际位置存储在字符串数组中。

NEEDS THAT CAN BE MADE:可以满足的需求:

But then you ask:但是你问:

  • But what about when I'm going to convert String to a floating point value?但是当我要将 String 转换为浮点值时呢? My answer is that you use the second matrix of this entire process (the one that receives the inversion of the first matrix that obtains the numbers by the palindrome method) and use it for the conversion, but always making sure, when necessary, of the position of the decimal place in future situations, in case this conversion (Double -> String) is needed again.我的回答是,您使用整个过程的第二个矩阵(接收通过回文方法获得数字的第一个矩阵的求逆的那个)并将其用于转换,但在必要时始终确保在将来的情况下小数位的位置,以防再次需要此转换(双 -> 字符串)。

But what if the problem is to use the value of the converted Double (Array of Strings) in a calculation.但是,如果问题是在计算中使用转换后的 Double(字符串数组)的值怎么办。 Then in this case you went around in circles.然后在这种情况下,你绕着圈子转。 Well, the original variable will work anyway even with scientific notation.好吧,即使使用科学记数法,原始变量也将起作用。 The only difference between floating point and decimal variable types is in the rounding of values, which depending on the purpose, it will only be necessary to change the type of data used, but it is dangerous to have a significant loss of information, look here浮点和十进制变量类型之间的唯一区别在于值的舍入,这取决于目的,只需要更改所使用的数据类型,但是有大量信息丢失是危险的,看这里

I could be wrong, but isn't it like this?我可能是错的,但不是这样吗?

data.ToString("n");

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

i think you need only to use IFormat with我认为你只需要使用 IFormat

ToString(doubleVar, System.Globalization.NumberStyles.Number)

example:例子:

double d = double.MaxValue;
string s = d.ToString(d, System.Globalization.NumberStyles.Number);

My solution was using the custom formats.我的解决方案是使用自定义格式。 try this:试试这个:

double d;
d = 1234.12341234;
d.ToString("#########0.#########");

This works fine for me...这对我来说很好......

double number = 1.5E+200;
string s = number.ToString("#");

//Output: "150000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

只是建立在 jcasso 所说的基础上,您可以做的是通过更改指数来调整您的 double 值,以便您最喜欢的格式会为您执行此操作,应用格式,然后用零填充结果以补偿调整。

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

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