Reputation: 880
The ToString() of a double value, causes losing of the decimal places
(1521.6666666666667).ToString() ==> "1521.66666666667"
Is there any way to save all the decimal places when converting to string
Also
(1521.6666666666667).ToString("F13"); => "1521.6666666666700"
(1521.6666666666667).ToString("0.0000000000000"); => "1521.6666666666700
Does this have to do with size of the double value
Upvotes: 4
Views: 2013
Reputation: 7213
Use The Round-trip ("R") Format Specifier, which will attempts to ensure that a numeric value that is converted to a string is parsed back into the same numeric value. This format is supported only for the Single
, Double
, and BigInteger
types.
But for Double
and Single
values, the "R" format specifier in some cases fails to successfully round-trip the original value and also offers relatively poor performance. Instead, we recommend that you use the "G17" format specifier for Double
values and the "G9" format specifier to successfully round-trip Single values.
From MSDN:
In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the
/platform:x64
or/platform:anycpu
switches and run on 64-bit systems.
Resource: Standard Numeric Format Strings.
Upvotes: 1
Reputation: 42354
decimal d = 1521.6666666666667M;
d.ToString();
According to the documentation:
Compared to floating-point types, the decimal type has more precision and a smaller range.
Specifically, decimal
has 28-29 significant digits, rather than 15-16 for double
.
Upvotes: 2
Reputation: 186668
You can use Decimal
instead of Double
:
(1521.6666666666667M).ToString(); // note "M"
Another possibility (if you have to use Double
) is "R" format:
(1521.6666666666667).ToString("R");
Upvotes: 1
Reputation: 62093
The solution to this is reading the documentation. Seriously It is NOT "ToString" that is loosing it.
Let me quote the float data Type from https://msdn.microsoft.com/en-us/library/b1e65aza.aspx:
Precision: 7 digits.
The numbers are in your source, they are never in the float. Not properly. The value is rounded.
Upvotes: 4