PUG
PUG

Reputation: 4472

Double.Parse losing precision when converts 8 decimal places string

i am trying to convert "12345678.12345678" to double, but Double.Parse changes it 12345678.123457. Same is the case when i use Decimal instead of double

   decimal check = Decimal.Parse("12345678.12345678", NumberStyles.AllowDecimalPoint);//returns 12345678.123457
    double check1 = (Double)check; //returns 12345678.123457

Upvotes: 1

Views: 3361

Answers (5)

N_A
N_A

Reputation: 19897

There are two things going on here:

  1. A decimal to double conversion is inexact/the double type has precision which does not map to whole numbers well (at least in a decimal system)

  2. Double has a decimal place limit of 15-16 places

Reference for decimal to double conversion;

Upvotes: 0

RajeevNy
RajeevNy

Reputation: 28

Just a quick test gave me the correct value. double dt = double.Parse("12345678.12345678"); Console.WriteLine(dt.ToString());

Upvotes: 0

Richard
Richard

Reputation: 108995

Floating point types haves only so many significant digits: 15 or 16 in the case of System.Double (the exact number varies with value).

The documentation for System.Double covers this.

A read of What Every Computer Scientist Should Know About Floating-Point Arithmetic is worth while.

Upvotes: 1

Steven Evers
Steven Evers

Reputation: 17196

If you take a look at the page for the double datatype you'll see that the precision is 15-16 digits. You've reached the limit of the precision of the type.

I believe Decimal might be what you're looking for in this situation.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

Floating point arithmetic with double precision values inherently has finite precision. There only are 15-16 significant decimal digits of information in a double precision value. The behaviour you see is exactly to be expected.

The closest representable double precision value to 12345678.12345678 is 12345678.1234567798674106597900390625 which tallies with your observed behaviour.

Upvotes: 4

Related Questions