0

Here is my simple code:

string t = "65.2";
var d = Convert.ToDouble(t);

and it gives me this error:

input string was not in a correct format on Convert.ToDouble

I have tried Convert.ToDobule(t, CultureInfo.InvariantCulture); and also Convert.ToDobule(t, new CultureInfo("en-US")); it works fine on my machine, but on another with the same culture it will give the same error.

where is the problem? and how to solve it?

Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • 13
    You're probably in a culture where the decimal separator is `,`, not `.`. Try specifying a culture where the decimal separator is `.` such as the invariant culture, e.g. `Convert.ToDouble(t, CultureInfo.InvariantCulture)` – canton7 Jan 19 '22 at 15:56
  • 2
    As and addition to @canton7, I wuld prefer double.TryParse. ie: double.TryParse("65.2", System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US"), out double v); Console.WriteLine(v); – Cetin Basoz Jan 19 '22 at 16:00
  • 2
    @CetinBasoz If you're going to use `TryParse`, check the return result before using `v`! But agreed, `double.Parse` / `double.TryParse` is preferable to the `Convert` methods – canton7 Jan 19 '22 at 16:08
  • @canton7, yes I meant to check but in comments it was even bad for a small piece of code:) – Cetin Basoz Jan 19 '22 at 18:00
  • I have tried `Convert.ToDobule(t, CultureInfo.InvariantCulture);` and also `Convert.ToDobule(t, new CultureInfo("en-US"));` it works fine on my machine, but on another with the same culture it will give the same error I mentioned in question :( – Inside Man Jan 19 '22 at 18:12
  • @canton7 I have updated my question – Inside Man Jan 19 '22 at 18:47
  • I believe you are hiding the actual input value and code. That wouldn't cause such an error. Also, as I said, prefer TryParse instead. – Cetin Basoz Jan 19 '22 at 18:52
  • @CetinBasoz The actual code is the same. I did not hide anything. it is so simple and I can not find the problem. I even checked both system languages settings. They are the same. – Inside Man Jan 19 '22 at 19:11
  • That code wouldn't cause such an error message. Maybe your error is coming from a nother part of your code? – Cetin Basoz Jan 19 '22 at 19:21

0 Answers0