简体   繁体   中英

How to format a double with more digits?

I have a double value and I want to convert it to a string with more than the default 15 digits. How can I accomplish this?

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

I have a double value and I want to convert it to a string with more than the default 15 digits.

Why? It's basically going to be garbage after 15 digits. You can get the exact value using my DoubleConverter class:

string exact = DoubleConverter.ToExactString(value);

... but after 15 digits, the rest is just noise.

If you want more than 15 significant digits of meaningful data, use decimal .

It is not possible with double as it does not support a precision of more than 15 digits. You can try using decimal data type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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