Trouble converting string to double
Hello,
I have trouble in converting string to double. I am using following code:
Code:
float[] aData = new float[0];
aData[0] = System.Convert.ToSingle(s.ToString(), CultureInfo.CurrentUICulture); /** doesn't matter if I use Culture info or not */
//or
float.TryParse(s.ToString(), NumberStyles.AllowDecimalPoint, CultureInfo.CurrentUICulture, out aData[0]);
If my string is 123.56 then output in aData[0] (followed in memory) is 123.560000000000003. I do not know from where I am getting 3 in the end. It is sometimes 1, sometimes 2 etc. The best example I could find was: if the input string is 981.55, the coversion to double results in 981.54999999999995
Any hint how can I correct it?
Regards
Ricky
Re: Trouble converting string to double
There's always
Code:
float temp = aData[0] * 100;
temp = (int)temp;
temp /= 100;
aData[0] = temp;
I'm more curious about the new float[0]. Isn't that giving you any errors? You're initializing an array of size 0...
Re: Trouble converting string to double
Sorry, the code written above does not represent the actual code in my program. aData is argument which I initialized as local in above code just for better understanding of reader.
I checked your code written above. This will return 981.54 but not 981.55 which is the actual value I have recieved. Isnt it?
Re: Trouble converting string to double
Code:
string s = "981.55";
double d;
if (double.TryParse(s, NumberStyles.AllowDecimalPoint,CultureInfo.InvariantCulture,out d))
Console.WriteLine(d);
else
Console.WriteLine("Fail");
this outputs 981.55 in the console
Re: Trouble converting string to double
Yes, you are right, it would be rounding wrong. And if you search for a Round method, you get an even better solution.
Code:
// double Math.Round(double value, int digits)
double value = System.Convert.ToSingle(s.ToString(), CultureInfo.CurrentUICulture); // or double.Parse/TryParse or whatever you like.
double roundedValue = Math.Round(value, 2); // will give value with two decimal digits
Re: Trouble converting string to double
I have come across an interesting article from NI
http://digital.ni.com/public.nsf/all...2565B000383C2F
It does not matter what one does, even a simple declaration of a double to 981.55 is not able to store it as 981.55 (exact). This is constraint in every operating system. Even rounding of does not help, but yes I can round of, convert it to a string and then make comaprison. That works.
Re: Trouble converting string to double
Quote:
123.560000000000003. I do not know from where I am getting 3 in the end.
Here is another paper you need to study.http://en.wikipedia.org/wiki/Floating_point