双精度浮点数转字符串,不使用科学计数法

104

如何在.NET框架中将double转换为浮点字符串表示形式,而不使用科学计数法?

"小"样本(有效数字可以是任何大小,例如1.5E2001e-200):

3248971234698200000000000000000000000000000000
0.00000000000000000000000000000000000023897356978234562

没有一个标准数字格式是这样的,自定义格式也似乎不允许在小数分隔符后有打开的数字位数。

这不是如何将double转换为字符串而不使用10表示法(E-05)的重复,因为那里给出的答案不能解决手头的问题。这个问题中被接受的解决方案是使用固定点(例如20位),这不是我想要的。固定点格式化和修剪冗余的0也无法解决问题,因为固定宽度的最大宽度是99个字符。

注意:解决方案必须正确处理自定义数字格式(例如其他十进制分隔符,具体取决于文化信息)。

编辑:这个问题实际上只涉及到显示前面提到的数字。我知道浮点数是如何工作的,以及可以使用和计算哪些数字。


1
您现在有这个问题的解决方案吗? - Kira
@Anand,有两个解决方案可行(Paul Sasik和我的),即使它们不是特别“好”(需要通过字符串操作)。 - Lucero
18个回答

55

对于一个通用解决方案,您需要保留339个位置:

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

非零小数位的最大数量为16。其中15个在小数点右侧。指数可以将这15个数字最多向右移动324个位置。(查看范围和精度。)

它适用于 double.Epsilon, double.MinValue, double.MaxValue 和介于它们之间的任何值。

与正则表达式/字符串操作解决方案相比,性能将更高,因为所有格式化和字符串处理都是由未托管的CLR代码一次完成的。此外,该代码更容易证明正确性。

为了使用方便和更好的性能,请将其设置为常量:

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

¹ 更新: 我错误地说这也是一种无损解决方案。事实上,它并不是,因为ToString对除r以外的所有格式都进行正常的显示舍入。示例链接。感谢@Loathing!如果您需要在固定点表示法中进行往返转换(即,如果您今天正在使用.ToString("r")),请参见Lothing的答案


虽然很简短,但如果您不需要极大的值,您可以快10倍。请参阅我的答案:https://dev59.com/6XI_5IYBdhLWcg3wDOnW#36204442 - ygoe
谢谢,运行得非常完美。你是一个了不起的人。已点赞。 - Snoop
1
这个解决方案不是“无损的”。例如:String t1 = (0.0001/7).ToString("0." + new string('#', 339)); // 0.0000142857142857143String t2 = (0.0001/7).ToString("r"); // 1.4285714285714287E-05相比,精度在小数点后面的位数上丢失了。 - Loathing

36

我有一个类似的问题,这个方法对我有效:

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

F99可能有点过头,但你可以理解它的意思。


1
99不够,而且它必须适用于逗号前后。 - Lucero
2
TrimEnd('0') 是足够的,因为 char 数组是 params。也就是说,传递给 TrimEnd 的任何 char 都将自动分组成一个数组。 - Grault
99对于通用解决方案来说是不够的。 doubleValue.ToString("0." + new string('#', 339))是无损的。 使用值double.Epsilon比较这些方法。 - jnm2

22

这是一种字符串解析方案,其中源数字(double)被转换为字符串并解析为其组成部分。然后按照规则重新组合成完整的数字表示形式。它还根据要求考虑了区域设置。

更新:转换测试仅包括单个数字,这是常态,但该算法也适用于像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();
    }
}

3
这个更容易阅读,因为你不需要理解正则表达式。 - Gregory
另一个改进方法是创建一个扩展方法:public static class MyClass,然后 public static string ToLongString(this double input)。这样你就可以像调用 d.ToString() 一样调用 d.ToLongString() - Ed Avis
为什么不使用更简单的 doubleValue.ToString("0." + new string('#', 339))?这样可以减少错误,提高性能。 - jnm2
@jnm2 实际上,我测试过,在最坏情况下(E-320),它比 doubleValue.ToString("0." + new string('#', 339)) 快约20%。对于不需要科学计数法的数字,它快了约300%。 - hannesRSA
@hannesRSA 我无法复制您的基准测试。使用 double.Epsilon,您的速度比 doubleValue.ToString("0." + new string('#', 339)) 慢了7.85%,比 doubleValue.ToString(constFormatString) 慢了11.44%。Gist - jnm2
显示剩余8条评论

20
你可以将double转换为decimal,然后使用ToString()方法。
(0.000000005).ToString()   // 5E-09
((decimal)(0.000000005)).ToString()   // 0,000000005

我还没有进行性能测试,不知道从64位 double 转换到128位 decimal 或使用超过300个字符的格式字符串哪种更快。噢,而且在转换过程中可能会出现溢出错误,但是如果您的值适合 decimal,那么这应该可以正常工作。

更新: 看来转换速度要快得多。使用其他答案中给出的准备好的格式字符串,一百万次格式化需要2.3秒,而转换只需要0.19秒。可以重复。这快了10倍。现在只与值范围有关了。


很不幸,这对于非常大或非常小的数字的给定规范不起作用。例如,((decimal)(1e-200)).ToString()返回0,这是错误的。 - Lucero
1
为了公平地进行比较,你应该将这种方法与 double.ToString("0.############################") 进行比较。根据我的测试,你的方法只快了3倍。无论如何,只有在你确定不需要打印小于 1e-28 的数字并且你的 double 不是很大时,才能得到有效的答案,而这两个条件都不是原始问题的限制。 - jnm2
2
这是一个相当不错的解决方案,前提是你知道值的范围。 - Artur Udod

8

这是我目前得到的,看起来可以工作,但也许有更好的解决方案:

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));

5
将一个非常小的双精度数加一只是你的想法,与问题本身无关。如果你不加d=d+1直接运行,你会发现它实际上显示为0.000.....0001。 - Lucero
2
没问题。double x = 1.0; for (int i = 0; i < 200; i++) x /= 10; Console.WriteLine(x); - Lucero
6
这是因为实际上只有15位数字是有意义的,但你可以使用指数将它们“移动”到非常大或非常小的范围。但如果你要把一个非常小的数字和比它大约15位数字以上的数字相加,就会超出有效数字的数量,由于较大的数字更显著,所以小部分将会丢失。因此,在类似范围内计算数字(例如添加1e-200和1e-200,或1+1,或1e200+1e200)是可行的,但混合这样的值将导致舍入较小的值。 - Lucero
解决方案“double x = 1.0; for (int i = 0; i < 200; i++) x /= 10; Console.WriteLine(x);”的问题在于结果受到印象,因为通过不精确值的累积除法会在结果中累积误差。更好的解决方案是减少除法的次数,以减少累积误差。例如,如果需要除以10的幂,则创建一个由10的倍数的10、1e10、1e100、1e1000等幂组成的数组,然后在循环中使用它们,并相应地递减循环控制变量。对于1e-200,((1.0 / 1e100) / 1e100)是精确的。另一种方法则不是。 - Julie in Austin
@朱莉,那并不是一种解决方案,它只是证明了通过计算可以得到如此小的数字(而不仅仅是通过定义常量值)。你当然是正确的关于不精确的值累积,但对于这个例子来说是无关紧要的。 - Lucero
显示剩余9条评论

7
使用#.###...###F99存在的问题是它无法保留小数点后的精度,例如:
String t1 = (0.0001/7).ToString("0." + new string('#', 339)); // 0.0000142857142857143
String t2 = (0.0001/7).ToString("r");                         //      1.4285714285714287E-05
< p > DecimalConverter.cs 的问题在于它速度较慢。这段代码与Sasik的答案相同,但速度快了一倍。底部是单元测试方法。

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();
            }
        }
    }
}

根据 .NET 文档,double.ToString("G17") 比 double.ToString("r") 更好。 - YantingChen
@YantingChen 我不同意使用 G17。在他们自己的示例中,0.6822871999174.ToString("G17") 输出为:0.68228719991739994 - Loathing
以下是两个讨论 double.Parse(...) 问题的链接:https://github.com/dotnet/runtime/issues/4406 和 https://github.com/dotnet/roslyn/issues/4221。 - Loathing

3

必要的对数解法。请注意,因为它涉及到数学计算,所以这种解法可能会稍微降低你数字的精度。未经过严格测试。

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');
    }
}

编辑:如果小数点穿过数字的非零部分,这个算法将会失败。我试图让它简单,但走得太远了。

谢谢您的建议,我会尝试实现一个完全可行的解决方案,并将其与我的进行比较。 - Lucero

3

谢谢你提供的链接,我已经尝试了Jon的代码,但是对于我的目的来说它有点太精确了;例如,0.1不会显示为0.1(这在技术上是正确的,但不是我所需要的)... - Lucero
是的,但你看,Jon的代码的整个目的就是要精确地显示数字,而这对我的情况来说有点过于复杂了。当使用ToString()进行四舍五入时,运行时所做的处理对我来说已经足够了,这也可能是为什么在这里提出的大多数解决方案都以ToString()作为进一步处理的基础的原因。 - Lucero
你好!我来自未来的十年,想告诉你Jon文章的超链接已经失效了。 - Nick Vaccaro

2

我刚刚对上面的代码进行了修改,使其适用于负指数值。

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);
                }
            }
        }
    }
}

这段代码接受一个输入目录,并基于分隔符将所有科学计数法表示的值转换为数字格式。

谢谢。


1
尝试这个:
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接