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

时间:2009-10-09 21:25:01

标签: c# .net floating-point number-formatting

如何在.NET Framework中没有科学记数法的情况下将double转换为浮点字符串表示形式?

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

3248971234698200000000000000000000000000000000
0.00000000000000000000000000000000000023897356978234562

standard number formats都不是这样的,custom format似乎也不允许在小数点分隔符后面有一个空位数。

这不是How to convert double to string without the power to 10 representation (E-05)的副本,因为那里的答案解决了手头的问题。这个问题中接受的解决方案是使用固定点(例如20位数),这不是我想要的。固定点格式化和修剪冗余0无法解决问题,因为固定宽度的最大宽度为99个字符。

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

编辑:问题实际上只是取代上述数字。我知道浮点数如何工作以及可以使用和计算哪些数字。

18 个答案:

答案 0 :(得分:27)

对于通用的解决方案,您需要保留339个地方:

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

非零小数位的最大数量为16. 15位于小数点的右侧。指数可以将这15个数字移动到右边最多324个位置。 (See the range and precision.

适用于double.Epsilondouble.MinValuedouble.MaxValue以及介于两者之间的任何内容。

性能将比正则表达式/字符串操作解决方案大得多,因为所有格式化和字符串工作都是通过非托管CLR代码一次完成的。此外,代码更容易证明是正确的。

为了便于使用,甚至提高性能,请将其设为常数:

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

¹更新:我错误地说这也是一种无损解决方案。实际上并非如此,因为除了ToString之外,r对所有格式进行正常显示舍入。 Live example.谢谢,@ Loathing!如果您需要以固定点表示法进行往返(即,如果您今天使用.ToString("r")),请参阅Lothing’s answer

答案 1 :(得分:25)

我有类似的问题,这对我有用:

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

F99可能过度,但你明白了。

答案 2 :(得分:18)

这是一个字符串解析解决方案,其中源编号(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 :(得分:10)

您可以将multi_filter'", "org/jruby/RubyArray.java:1613:in`each'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-1.5.0-java/lib/logstash/filters/base.rb:159:in multi_filter'", "(eval):67:in`filter_func'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-1.5.0-java/lib/logstash/pipeline.rb:219:in filterworker'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-1.5.0-java/lib/logstash/pipeline.rb:156:in 转换为double,然后执行decimal

ToString()

我没有进行性能测试,速度更快,从64位(0.000000005).ToString() // 5E-09 ((decimal)(0.000000005)).ToString() // 0,000000005 转换为128位double或格式字符串超过300个字符。哦,转换期间可能存在溢出错误,但如果您的值适合decimal,这应该可以正常工作。

更新:投射似乎要快得多。使用另一个答案中给出的准备好的格式字符串,格式化一百万次需要2.3秒并且仅投射0.19秒。重复。那个快10倍。现在它只是关于价值范围。

答案 4 :(得分:7)

这是我迄今为止所做的,似乎有用,但也许有人有更好的解决方案:

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 :(得分:3)

在过去我们必须编写自己的格式化程序时,我们会将尾数和指数分开并单独格式化。

在Jon Skeet(https://csharpindepth.com/articles/FloatingPoint)的这篇文章中,他提供了一个指向他的DoubleConverter.cs例程的链接,该例程应该完全符合你的要求。 Skeet也在extracting mantissa and exponent from double in c#指出这一点。

答案 6 :(得分:2)

使用#.###...###F99的问题在于它不会在小数点后的位置保留精度,例如:

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

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

答案 7 :(得分:2)

基于对数的强制解决方案。请注意,此解决方案,因为它涉及数学运算,可能会降低您的数字的准确性。未经过严格测试。

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

编辑:如果小数点越过数字的非零部分,则此算法将失败。我试着简单而且走得太远了。

答案 8 :(得分: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);
                }
            }
        }
    }
}

此代码采用输入目录,并基于分隔符将科学记数法中的所有值转换为数字格式。

由于

答案 9 :(得分: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;
}

答案 10 :(得分:0)

我不知道我对问题的回答是否仍然有帮助。但在这种情况下,我建议 “将 double 变量分解为小数位” 将其存储在 Array / String 类型的数据数组中。

这个分解和存储部分(逐个数字)从 double 到 string 的过程,基本上可以使用两个循环和一个“替代方法”(如果你想到了解决方法,我想你明白了),其中第一个循环将从 double 中提取值而不转换为 String,从而得到有福的科学记数法 并在数组中逐个存储数字。这将使用 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;
}

然后第二个循环反转 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--;
    }

***警告:有一个我没有注意的问题。在这种情况下,将没有“。” (浮点小数点分隔符或双精度数),所以这个解决方案不是通用的。但是如果使用小数点分隔符真的很重要,不幸的是,唯一的可能性(如果做得好,它将有很好的性能)是: **使用例程获取原始值小数点的位置,用科学记数法的那个——重要的是你知道这个浮点在一个数字之前,比如“长度”位置x,之后一个数字,例如 y 位置 - 使用循环提取每个数字 - 如上所示 - 最后将数据从最后一个数组“导出”到另一个数组,包括小数位分隔符(逗号或句点,如果变量十进制,双精度或浮点数)在原始变量中的虚位置,在该矩阵的“真实”位置。

*** 位置的概念是,找出小数点前有多少个数字,这样你就可以在字符串数组中存储实际位置的点。

可以满足的需求:

但是你问:

  • 但是当我要将 String 转换为浮点值时呢? 我的回答是您使用整个过程的第二个矩阵(接收通过回文方法获得数字的第一个矩阵的求逆的那个矩阵)并将其用于转换,但在必要时始终确保未来情况下小数点的位置,以防再次需要此转换(双 -> 字符串)。

但是如果问题是在计算中使用转换后的 Double(字符串数组)的值呢?那么在这种情况下,你就转了一圈。好吧,即使使用科学记数法,原始变量也将起作用。浮点和十进制变量类型的唯一区别在于值的四舍五入,这取决于目的,只需要更改使用的数据类型,但是大量丢失信息是危险的,看{ {3}}

答案 11 :(得分:0)

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

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

答案 12 :(得分:0)

作为全球数百万程序员,如果有人已经遇到问题,尝试搜索总是一个好习惯。有时候解决方案是垃圾,这意味着是时候编写自己的,有时也很棒,如下所示:

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

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

答案 13 :(得分:-1)

这对我来说很好......

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

//Output: "150000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

答案 14 :(得分:-1)

我的解决方案是使用自定义格式。 试试这个:

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

答案 15 :(得分:-1)

我认为您只需要使用IFormat

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

示例:

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

答案 16 :(得分:-1)

只是建立jcasso所说的你可以做的是通过改变指数调整你的双值,以便你最喜欢的格式为你做,应用格式,然后用零填充结果来补偿调整。

答案 17 :(得分:-1)

我可能错了,但是不是这样吗?

data.ToString("n");

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