1

I'm using visual studio code on windows, creating mvc app using latest asp.net core.

when I run this code:

string number = "13,89";
float convertedNumber = -1f;
bool result = float.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out convertedNumber);

I get result = true, indicating that parsing was successful, but actual convertedNumber = 1389;

I tried different cultures, different numberstyles and I just don't get it. I would understand getting result = false, but not this. and I have no idea how to fix it.

c# fiddle for convenience: https://dotnetfiddle.net/0ZDwis

Aristos
  • 66,005
  • 16
  • 114
  • 150
aacid
  • 199
  • 3
  • 13
  • 1
    `,` is a *thousand separator*, not a *decimal point* in case of *invariant culture*. If you put a specific culture, say, russian: `CultureInfo.GetCultureInfo("ru-RU")` you'll have `,` as decimal separator (and `.` will thousand separator) – Dmitry Bychenko Dec 17 '18 at 20:39
  • *"I tried different cultures"* did you try any that use `,` as a decimal point? – Rufus L Dec 17 '18 at 20:40
  • Is your question actually: Why does it not fail? – Silvermind Dec 17 '18 at 21:06
  • interestingly though thats not a valid string with , as the thousands separator – pm100 Dec 17 '18 at 22:11

2 Answers2

7

, is interpreted as a thousand separator, not a decimal point. For example, this will work:

string number = "13.89";

Or alternatively, use a culture where the comma is used as a decimal, for example French:

string number = "13,89";
float convertedNumber = -1f;
var culture = CultureInfo.GetCultureInfo("fr-FR");
bool result = float.TryParse(number, NumberStyles.Any, culture, out convertedNumber);
DavidG
  • 113,891
  • 12
  • 217
  • 223
4

If you want float.TryParse to treat the , as a decimal separator instead of a thousand separator, you should use a culture that has the comma as decimal separator, like Dutch:

bool result = float.TryParse(number, NumberStyles.Any, new CultureInfo("nl-nl"), out converted);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325