Tweak in Double.ToString() conversion

I am working on an application which involves lot of arithmetic operations. In this application we heavily make use of double and string interchangeably.
I was facing a problem with conversion between double type to string variables.

Consider below code;
1
2
double d = 30.235312769517968;
string convertedValue = d.toString();

If we see the output of convertedValue variable it gives us something like 30.235312769518, which fails the comparison.
To preserve the decimal precision we can make use of ToString() as below;

1
string convertedValue = d.ToString("R");

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

No comments:

Post a Comment