【问题标题】:How to format a double with more digits?如何格式化具有更多数字的双精度数?
【发布时间】:2013-03-25 19:24:11
【问题描述】:

我有一个双精度值,我想将其转换为超过默认 15 位数字的字符串。我怎样才能做到这一点?

(1.23456789987654321d).ToString(); // 1.23456789987654
(12.3456789987654321d).ToString(); // 12.3456789987654
(1.23456789987654321d).ToString("0.######################################"); // 1.23456789987654
(1.23456789987654321d).ToString("0.0000000000000000000000000000000"); // 1.2345678998765400000000000000000

【问题讨论】:

标签: c# double number-formatting


【解决方案1】:

double 不可能,因为它不支持超过 15 位的精度。 您可以尝试使用十进制数据类型:

using System;

namespace Code.Without.IDE
{
    public class FloatingTypes
    {
        public static void Main(string[] args)
        {
            decimal deci = 1.23456789987654321M;
            decimal decix = 1.23456789987654321987654321987654321M;
            double doub = 1.23456789987654321d;
            Console.WriteLine(deci); // prints - 1.23456789987654321
            Console.WriteLine(decix); // prints - 1.2345678998765432198765432199
            Console.WriteLine(doub); // prints - 1.23456789987654
        }
    }
}

【讨论】:

    【解决方案2】:

    我有一个双精度值,我想将其转换为超过默认 15 位数字的字符串。

    为什么? 15位数之后基本上就是垃圾了。您可以使用我的 DoubleConverter 类获得 exact 值:

    string exact = DoubleConverter.ToExactString(value);
    

    ...但在 15 位数之后,剩下的只是噪音。

    如果您想要超过 15 个有效数字的有意义数据,请使用decimal

    【讨论】:

    • DoubleConverter 类的行为与 ToString("R") 有何不同?
    • @ChaseMedallion:“R”只需提供足够的信息即可唯一地返回原始值(往返)。我的代码给出了双精度的 exact 值。
    • 它实际上不是噪音,特别是如果您正在验证您可以解析之前/之后的值 EXACTLY
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多