1

I am having an issue in C# trying to convert a decimal using Decimal.Parse with a decimal precision of 4 or more. It is throwing the error:

Input string was not in a correct format" when it tries to execute the function with the value 0.00006 or greater precision.

I have tried using InvariantCulture and ruled that out as the issue, as that is what I saw being recommended for others getting this error.

I have also tried using decimal.Parse to no avail.

The line of code being executed is:

Decimal decVal = Decimal.Parse(Value.ToString())

where value is the string "0.00006".

Has anyone else seen this problem before? Is this a problem inherent with the Decimal.Parse function, or is it something that I am doing?

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
  • 1
    Works for me - it's likely a culture issue (or there are non-visible characters in the string) – D Stanley Apr 08 '15 at 21:13
  • I edited your code a tad to use formatting, and in the process I swapped out one line of English description with a variable. Was everything I did correct, and does this code still reproduce your problem? I hate to change code this dramatically, but it needed to be formatted so I wanted to double-check. – Matthew Haugen Apr 08 '15 at 21:19
  • 3
    Programmers that call ToString() on a string do tend to have odd problems. Is it actually a string? – Hans Passant Apr 08 '15 at 21:23
  • @HansPassant If I had to guess I'd say it was a float. The `ToString()` call would result in scientific notation at that precision which would fail on the `decimal.Parse` – petelids Apr 08 '15 at 22:11
  • @DStanley How would I know if there are non-visible characters in the string? In the debugger it looks like it is just that string, but is it still possible there could be extra characters in there somehow that I am not seeing? petelids and Hans Passant I don't think it is a float, I tried casting into a Decimal and that did not work which would work if it were a float. It is an object which is a string. The odd thing is it will work with any decimal precision below 4, so it is something about the amount of precision that is causing it to error. – David Schunemann Apr 09 '15 at 13:56

1 Answers1

3

I figured it out. Turns out the ToString was returning scientific notation when precision goes beyond 4 places, so the fix was to use the following code:

Decimal decVal = Decimal.Parse(Value.ToString(), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint)

Figured it out from reading through this question: How to convert this scientific notation to decimal?

Thanks to everyone who offered input!

Community
  • 1
  • 1