[ACCEPTED]-TryParse failing with negative numbers-tryparse

Accepted answer
Score: 11

This is not how you are supposed to use 2 TryParse.

TryParse returns a boolean (true/false), so 1 your code above should be:

private decimal CalculateValue(IEnumerable<XElement> summaryValues)
        {
            decimal totalValue = 0;

            foreach (XElement xElement in summaryValues)
            {
                decimal valueReturned;
                bool successful = Decimal.TryParse(xElement.Value, out valueReturned);
                if (successful)
                    totalValue += valueReturned;
            }
            return totalValue;
        }

or more succinctly,

private decimal CalculateValue(IEnumerable<XElement> summaryValues)
        {
            decimal totalValue = 0;

            foreach (XElement xElement in summaryValues)
            {
                decimal valueReturned;
                if (Decimal.TryParse(xElement.Value, out valueReturned))
                    totalValue += valueReturned;
            }
            return totalValue;
        }
Score: 4

Others are explaining how to do it right, but 15 not really explaining what you're doing 14 wrong.

Where you're using "successful" above 13 isn't the success value, it's the actual 12 number that is being parsed. So if you're 11 parsing "-150.00" of course successful will 10 be negative. The out value of TryParse 9 is the actual parsed value and the boolean 8 indicating whether the process was successful 7 or not is the returned value. Using what 6 you have to help understand would be something 5 like:

string inputValue = "-150.00";
decimal numericValue;
bool isSucessful = Decimal.TryParse(inputValue , out numericValue);

In this case, isSuccessful will be 4 TRUE, numericValue will be -150. When you're 3 using user-provided values instead of the 2 hardcoded one I used above you'll want to 1 check:

if(isSuccessful)
{
    // Do something with numericValue since we know it to be a valid decimal
}
else
{
    // Inform User, throw exception, etc... as appropriate, Don't use numericValue because we know it's wrong.
}
Score: 3

The other answers have got the right idea 7 with regard to the proper way to use Decimal.TryParse. However, if 6 I were writing the method in question, I'd 5 use LINQ to work with LINQ-to-XML objects:

private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
    return summaryValues
        .Sum(el =>
             {
                 decimal value;
                 if (Decimal.TryParse(el.Value, out value))
                     return value;
                 return 0M;
             });
}

This 4 version works the exact same way, but it 3 uses the Enumerable.Sum method to calculate the total. All 2 I have to supply is an inline function that 1 extracts decimal values from an XElement.

Score: 3

Came in from Google. Answer for me was the 2 incoming culture was wrong - specifically 1 in an incoming JSON file.

Use

totalValue += decimal.Parse(xElement.Value, NumberStyles.Any, CultureInfo.InvariantCulture);

or

bool successful = decimal.TryParse(xElement.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
Score: 1

your successful is going to be negative 5 for a negative value being parsed. your 4 if (successful > 0) is what's tripping you up.

If they are almost 3 positively going to be valid values, try 2 using Convert.ToDecimal:

decimal val = Convert.ToDecimal(xElement.Value);

Otherwise, change your logic a bit 1 to be more like:

decimal val;
if (Decimal.TryParse(xElement.Value, out val)){
  // valid number
}
Score: 0

I would suggest you to tell XElement which 3 node value it should look for as in:

XElement.Element("nodename").Value

Instead 2 of XElement.Value. at least that is what 1 I would do :)

More Related questions