문제

I am currently trying to parse a string, "277.968", to decimal, but I am getting a FormatException exception.

I have read that I need to perform the decimal parse this way:

string str = "277.968";
decimal.Parse(str, CultureInfo.InvariantCulture);

Still, I am getting the said exception.

What could I do?

EDIT: Fixed float to decimal

도움이 되었습니까?

해결책

Printing the lenght of the string, it reported it being 80 chars long.

Right, well that's the problem then. Your string isn't "277.968" - it's "277.968\0\0\0\0\0\0(...)" - and that can't be parsed.

My guess is that you've read this from a TextReader of some kind, but ignored the return value of Read, which is the number of characters that have been read.

So for example, if your current code is effectively:

char[] risul = new char[80];
reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul), CultureInfo.InvariantCulture);

then you should instead have:

char[] risul = new char[80];
int charsRead = reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul, 0, charsRead),
                              CultureInfo.InvariantCulture);

... although that's still assuming that you're reading all of the appropriate data in a single call to Read, which isn't necessarily the case. You may well just want:

string data = reader.ReadToEnd();
decimal value = decimal.Parse(data, CultureInfo.InvariantCulture);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top