Double.ToString round-trip: "R" vs. "G17"
- From: "Jason Frank" <mabraham36@xxxxxxxxxxxxxxxx>
- Date: Wed, 25 May 2005 13:38:44 -0400
One aspect of an application I'm working on requires doubles to be sent to a
browser in XML, and therefore the doubles have to be represented as strings.
We also need to be able to take the XML back from the browser and parse the
doubles, and have them turn into the "same" double as before it was sent to
the browser. So we're using the double as a kind of identifier. Let's
leave aside whether this is a good design -- clearly it is not, given
various issues with double equality comparison and translation to and from
decimal string representation, but at this point it would be a major
investment to revamp our application to use some other way of identifiying
the entities we are passing back and forth.
Using the normal Double.ToString() call in creating the XML does not get the
job done -- there are doubles that do not parse back to the same value when
round-tripped using plain Double.ToString(). I have read about the "R"
format string, which is guaranteed to create a string representation of a
double that will parse back to the same double (apart from possible outliers
like Double.MaxValue, which do not parse). However, the description for the
"R" format makes me wonder why it wouldn't be better to use a format like
"G17" instead. The description for "R" indicates that it will output the
number with 15 decimals, parse that back to a double, and if it's the same
as the original double, it's done, otherwise output it with 17 decimals.
This sounds expensive. Why not just go straight to 17? You might think
that the resulting string will be bigger than necessary. However, my
experience with "G17" is that it will not output 17 decimals unless the
number actually needs 17 decimals. For example, if you take the number 1.0,
and output it using "G17", you get "1". Perhaps it's doing the same thing
behind the scenes as "R" -- outputting the number with fewer decimals,
parsing it back and checking for equality, etc, in which case I still don't
see what the advantage of using "R" is.
Basically, my question boils down to this: if the "R" format uses 17
decimals as a worst case in order to ensure round-trip preservation, how
could there be a number such that "G17" does not preserve its value in a
round trip? Why would I use the "R" format instead of "G17"?
Thanks for any light you can shed on this issue.
.
- Follow-Ups:
- RE: Double.ToString round-trip: "R" vs. "G17"
- From: "Jeffrey Tan[MSFT]"
- RE: Double.ToString round-trip: "R" vs. "G17"
- Prev by Date: ILMerge and Linking the Runtime
- Next by Date: Re: ILMerge and Linking the Runtime
- Previous by thread: ILMerge and Linking the Runtime
- Next by thread: RE: Double.ToString round-trip: "R" vs. "G17"
- Index(es):
Relevant Pages
|