1

I'm trying to convert a string "8.7" to a number, but all my tries convert it to 87 not to 8.7. Here is how I tried.

string wind_kph = "8.7"
if (Convert.ToDouble(wind_kph) > 60.00f)

true

if ((int)Convert.ToDouble(wind_kph) > 60.00f)

true

if (Convert.ToDecimal(wind_kph) > 60.00f)

true

MethodMan
  • 18,625
  • 6
  • 34
  • 52
Aman
  • 582
  • 2
  • 12
  • 29
  • 3
    Do you have any localization settings that could be interfering with the parse? I believe the decimal point is a comma in some cultures. The code you have looks like it *should* work though. – BradleyDotNET Jul 01 '14 at 18:52
  • What is your local culture? Many Eurppean cultures treat `"8.7"` as `87`, and `"8,7"` as `8.7`; I suspect you can fix a lot here simply by explicitly specifying a culture (perhaps the invariant culture). – Marc Gravell Jul 01 '14 at 18:53
  • The first line should be ";" terminated. How it compiles w/syntax error? Rgds, – Alexander Bell Jul 01 '14 at 18:55
  • There is no problem with your code and it works fine when I tried with it. – RajeshKannan Jul 01 '14 at 18:55
  • @AlexBell you are right, the code is bigger and I resumed and forgot the ; – Aman Jul 01 '14 at 19:05
  • The problem was my language selection, fixed it with InvariantCulture Thanks – Aman Jul 01 '14 at 19:06
  • No problem. Actually, it's quite interesting question. Thanks for bringing it to our attention. Rgds, – Alexander Bell Jul 01 '14 at 19:06

2 Answers2

4

You can use InvariantCulture for parsing which uses dot as a decimal separator

if(double.Parse(wind_kph, CultureInfo.InvariantCulture) > 60.00)

You can find more detailed information from the documentation of double.Parse(string) method, the relevant part is:

The s parameter is interpreted using the formatting information in a NumberFormatInfo object that is initialized for the current thread culture. For more information, see CurrentInfo. To parse a string using the formatting information of some other culture, call the Double.Parse(String, IFormatProvider) or Double.Parse(String, NumberStyles, IFormatProvider) method.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Thanks, this was the problem. My language selection was only recognizing a , not a . – Aman Jul 01 '14 at 19:03
3

It is probably a culture problem. If not explicitly specified the parsing functions use the current thread culture. To specify a specific culture you can send a 2nd parameter to the double.Parse function. In your case for "." you can use InvariantCulture.

double.Parse("8.7", CultureInfo.InvariantCulture);
Magnus
  • 45,362
  • 8
  • 80
  • 118