c#转换为字符串时如何防止双值截断

kwi*_*iri 1 c# type-conversion

Double x = 11.123456789123456;
string y = Convert.ToString(x);
//gives y=11.1234567891235
//y should be =11.123456789123456
Run Code Online (Sandbox Code Playgroud)

从上面的代码我怎样才能防止最后一个数字(6)被截断

xan*_*tos 6

使用

string y = x.ToString("G17");
Run Code Online (Sandbox Code Playgroud)

要么

string y = x.ToString("R");
Run Code Online (Sandbox Code Playgroud)

作为写在这里:

默认情况下,返回值仅包含15位精度,但内部最多保留17位数.如果此实例的值大于15位,ToString将返回PositiveInfinitySymbol或NegativeInfinitySymbol而不是预期的数字.如果您需要更高的精度,请指定格式为"G17"格式规范,它始终返回17位精度,或"R",如果数字可以用该精度表示,则返回15位数,如果数字只能表示,则返回17位数以最大精度表示.

请注意,并非所有数字都可以准确表示......

11.123456789123458.ToString("G17") == "11.123456789123457"
Run Code Online (Sandbox Code Playgroud)