If I wanted to convert a double to a string and back to a double that matches exactly, I would use something like:
double d1 = 1 / 3.0;
string s = d1.ToString("R");
double d2 = double.Parse(s);
But, the "R" format isn't defined for a decimal type (you get a "FormatException: Format specifier was invalid").
What is the way to produce a round-trip string for a decimal type?
The default output format for decimal
round-trips, so you don't have to do anything special. It is just like int
in that sense.
Decimal
is in fact a binary-decimal value (it uses base of 10 , not 2 as in Double
) and that's why there's no need to special exact representations like ToString("R")
;
Decimal value = 123.456m;
String result = value.ToString(CultureInfo.InvariantCulture); // <- That's enough
See also for details:
If you try,
decimal d1 = 1m / 3;
string s = d1.ToString();
decimal d2 = decimal.Parse(s);
// where d1 == d2 = true
You will see you do not need any extra formatting options to obtain a proper string
representation.
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.