-1

While parsing the string to double we are facing a issue. we need to convert 18 digit string(<123,456,789,012>.<123456>) to double. It returns only 5 digits after the decimal. When we tried to reducing the no of digits, it worked fine. We have attached the screenshot with three different scenarios. Variable 'S' is the input and retValue is the output value.

Kindly help us in converting 123,456,789,012.123456 to 123456789012.123456

string s = "123,456,789,012.123456"; 
double retVal; 
System.Globalization.CultureInfo cInfo = new System.Globalization.CultureInfo(System.Web.HttpContext.Curr‌​ent.Session["culture‌​"].ToString()); 
retVal = double.Parse(s, NumberStyles.Any, cInfo);

Issue screen shot

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 3
    Show us what you have tried? ;) Ok, it's in your screenshot. Why not adding it as code in your question? Would be easier for all of us. – Mighty Badaboom Apr 04 '17 at 11:08
  • It might be possible that the value to parse cannot be exactly represented in the `double` type. – Codor Apr 04 '17 at 11:10
  • we have added it in the Issue screen shot – Senthilraja Natarajan Apr 04 '17 at 11:11
  • 1
    `Decimal.Parse` https://msdn.microsoft.com/en-us/library/system.decimal.parse(v=vs.110).aspx – Igor Apr 04 '17 at 11:12
  • 2
    A screenshot isn't code that can be tried. Post the code and what you expected. Although the string you posted *CAN'T* be represented as a double without losing precision. Use `decimal` instead – Panagiotis Kanavos Apr 04 '17 at 11:12
  • double has only up to 15 significant digits precision so use decimal instead http://stackoverflow.com/questions/13542944/how-many-significant-digits-have-floats-and-doubles-in-java – Slai Apr 04 '17 at 11:15
  • 1
    Possible duplicate of [Why does Convert.ToDecimal(Double) round to 15 significant figures?](http://stackoverflow.com/questions/20495306/why-does-convert-todecimaldouble-round-to-15-significant-figures) –  Apr 04 '17 at 11:20

2 Answers2

6

A double has a precision of up to 15 digits, see MSDN:

A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

You should use decimal and Decimal.Parse(..) that has 28-29 significant digits.

xanatos
  • 109,618
  • 12
  • 197
  • 280
3

You are running into a precision issue that is inherent to all floating point data types like double. If you need more exact precision, you should be using decimal instead:

string s = "987,654,321.123456";
decimal d = decimal.Parse(s);

See it in action: https://repl.it/Gtoy/0

EDIT: As Panagiotis Kanavos points out, decimal isn't perfect either. It uses 128 bits as opposed to double's 64. However, where double uses its bits to represent larger numbers, decimal uses it to represent smaller numbers with much greater accuracy.

Abion47
  • 22,211
  • 4
  • 65
  • 88