Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, September 9, 2013 3:15 PM
Hello
string s1 = "-0.85";
double d1=0;
try
{
d1 = Convert.ToDouble(s1);
}
catch (FormatException)
{
Console.WriteLine("Something is wrong");
}
How to convert such kind of strings to double?
http://msdn.microsoft.com/ru-ru/library/zh4hkw6k.aspx I used this, but still I get exception
All replies (5)
Monday, September 9, 2013 3:31 PM ✅Answered | 1 vote
"-0.85" is probably not valid with your current default locale. Use the Convert overload that take an IFromatProvider
d1 = Convert.ToDouble(s1, System.Globalization.CultureInfo.GetCultureInfo("en-US"));
Monday, September 9, 2013 3:34 PM ✅Answered
You should specify an IFormatProvider:
string s1 = "-0.85"; double d1=0; try { Double.TryParse(s1, NumberStyles.Any, CultureInfo.InvariantCulture, out d1); } catch (FormatException) { Console.WriteLine("Something is wrong"); }
Monday, September 9, 2013 3:35 PM ✅Answered
The code seems to work for me, could you try the following and confirm it works?:
string x = "-0.85";
double d = Convert.ToDouble(x, CultureInfo.InvariantCulture);
Monday, September 9, 2013 3:36 PM ✅Answered
I think this is related to the culture you are working in, ru-RU? Convert.ToDouble() will use the current culture's number styles when attempting to do the conversion. If you set a format provider when calling the method it should get round the problem. See here for more.
Monday, September 9, 2013 3:42 PM ✅Answered
Well, it works for me :) The problem imho is the missing i18n. Use
namespace ConsoleApplication1
{
using System;
using System.Globalization;
public class Program
{
public static void Main(string[] args)
{
string s1 = "-0.85";
double d1 = 0;
try
{
d1 = Convert.ToDouble(s1, CultureInfo.InvariantCulture);
Console.WriteLine("Done");
}
catch (FormatException)
{
Console.WriteLine("Something is wrong");
}
Console.ReadLine();
}
}
}