简体   繁体   中英

C# double type formatting

I'm trying to convert C# double values to string of exponential notation. Consider this C# code:

double d1 = 0.12345678901200021;
Console.WriteLine(d1.ToString("0.0####################E0"));
//outputs: 1.23456789012E-1 (expected: 1.2345678901200021E-1)

Can anyone tell me the format string to output "1.2345678901200021E-1" from double d1, if it's possible?

Double values only hold 15 to 16 digits, you have 17 (if I counted right). Because 64 bit double numbers only hold 16 digits, your last digit is getting truncated and therefore when you convert the number to scientific notation, the last digit appears to have been truncated.

You should use Decimal instead. Decimal types can hold 128 bits of data, while double can only hold 64 bits.

According to the documentation for double.ToString() , double doesn't have the precision:

By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.

Console.WriteLine(d1) should show you that double doesn't support your wanted precision. Use decimal instead (64bit vs 128bit).

我的直接窗口是说,你可以从这个double号中得到的最大分辨率大约是15位数。

My VS2012 immediate window is saying that the resolution of 0.12345678901200021 is actually 16 significant digits:

0.1234567890120002

Therefore we expect that at least the last "2" digit should be reported in the string.

However if you use the "G17" format string:

0.12345678901200021D.ToString("G17");

you will get a string with 16 digit precision. See this answer .

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