Wrong result with double.Parse()

  • Thread starter Thread starter schlied
  • Start date Start date
S

schlied

Hello,

i have the following problem in our project:
If I try to parse a string value with the following line
double x = double.Parse("39.95238", CultureInfo.InvariantCulture);
x contains 39.9523799999.... instead of the correct one.
What could be the reason for that?

Thanks in advance

Chris
 
Hello,

i have the following problem in our project:
If I try to parse a string value with the following line
double x = double.Parse("39.95238", CultureInfo.InvariantCulture);
x contains 39.9523799999.... instead of the correct one.
What could be the reason for that?

Thanks in advance

Chris

The reason would be that floating point types are not accurate, and
store an approximation of the value. You'll find that you will
frequently notice two variations of this, either slightly lower
(.99999999) or slightly higher (.0000000001).

Try using Decimal, or just format the value for output to round to a
specific number of digits.
 
Double cannto guarantee to exactly represent every value, due to the
nature of floating-point arithmetic.

It sounds like you actually want a decimal; try:

decimal x = decimal.Parse("39.95238", CultureInfo.InvariantCulture);

Marc
 
Hello,

i have the following problem in our project:
If I try to parse a string value with the following line
double x = double.Parse("39.95238", CultureInfo.InvariantCulture);
x contains 39.9523799999.... instead of the correct one.

Looks right to me... 7.9 repeating is equal to 8. Even if not repeating,
the total error is what, less than one trillionth of a percent?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top