Double x = 11.123456789123456;
string y = Convert.ToString(x);
//gives y=11.1234567891235
//y should be =11.123456789123456
From the above code how can I prevent the last digit(6) from being truncated
Use
string y = x.ToString("G17");
or
string y = x.ToString("R");
as written here :
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.
Note that not all the numbers can be represented exactly...
11.123456789123458.ToString("G17") == "11.123456789123457"
The reason this is happening is because Double occupies 8 bytes and has precision of 15-16 digits. Use Decimal instead
Decimal x = 11.123456789123456M;
string y = Convert.ToString(x);
//gives y=11.12345678912356
Refer this link , look for answer by cds333
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.