0

I want to convert a value from string to float in c#. the value definitely has precision(I mean .00 or .67 in this example. I don't know the word in English for sure) like "120.00" , "233.67"

and this is what I do for doing that

   float existingValue = float.Parse(param[1].ToString());

param[1] contains the string value

but gives me error :

'Input string was not in a correct format.'

If I change the value from "120.00" to "120" it works fine

what is the problem for that?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
nnmmss
  • 2,850
  • 7
  • 39
  • 67
  • 3
    I assume in your current culture the `,` is the decimal separator instead of the `.` – fubo Feb 21 '22 at 11:55
  • 1
    Is it working if you parse `"120,00"` instead of `"120.00"`? – SᴇM Feb 21 '22 at 11:56
  • Sidenote: If `param[1]` is already a `string` then calling `param[1].ToString()` is pointless. – Matthew Watson Feb 21 '22 at 11:58
  • It's not as simple as it just being because '.' is the thousands separator in the current culture, because in that case it would parse to `12000`. It seems that the '.' is not being parsed as a decimal mark OR a thousands separator. I don't know what locale that would occur in... – Matthew Watson Feb 21 '22 at 12:02

1 Answers1

1

You should use an overload of float.Parse method. Specify IFormatProvider as an argument (e. g. CultureInfo.InvariantCulture or a specifc one) or NumberStyles.