简体   繁体   English

C#双重格式化

[英]C# double type formatting

I'm trying to convert C# double values to string of exponential notation. 我正在尝试将C#double值转换为指数表示法的字符串。 Consider this C# code: 考虑一下这个C#代码:

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? 任何人都可以告诉我格式字符串从双d1输出“1.2345678901200021E-1”,如果可能的话?

Double values only hold 15 to 16 digits, you have 17 (if I counted right). 双值只能容纳15到16位数,你有17位(如果我算的是右边)。 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. 由于64位双数字仅保留16位数字,因此您的最后一位数字会被截断,因此当您将数字转换为科学计数法时,最后一位数字似乎已被截断。

You should use Decimal instead. 你应该使用十进制。 Decimal types can hold 128 bits of data, while double can only hold 64 bits. 十进制类型可以保存128位数据,而double只能保存64位。

According to the documentation for double.ToString() , double doesn't have the precision: 根据double.ToString()的文档double没有精度:

By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. 默认情况下,返回值仅包含15位精度,但内部最多保留17位数。 If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. 如果此实例的值大于15位,ToString将返回PositiveInfinitySymbol或NegativeInfinitySymbol而不是预期的数字。 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. 如果您需要更高的精度,请指定格式为“G17”格式规范,它始终返回17位精度,或“R”,如果数字可以用该精度表示,则返回15位数,如果数字只能表示,则返回17位数以最大精度表示。

Console.WriteLine(d1) should show you that double doesn't support your wanted precision. Console.WriteLine(d1)应该显示double不支持你想要的精度。 Use decimal instead (64bit vs 128bit). 使用decimal代替(64位对128位)。

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

My VS2012 immediate window is saying that the resolution of 0.12345678901200021 is actually 16 significant digits: 我的VS2012即时窗口显示0.12345678901200021的分辨率实际上是16位有效数字:

0.1234567890120002

Therefore we expect that at least the last "2" digit should be reported in the string. 因此,我们期望至少应该在字符串中报告最后的“2”数字。

However if you use the "G17" format string: 但是,如果您使用“G17”格式字符串:

0.12345678901200021D.ToString("G17");

you will get a string with 16 digit precision. 你会得到一个16位精度的字符串。 See this answer . 看到这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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