Nick Weidemann
Nick Weidemann

Reputation: 9

How to convert a string to decimal for Summing using Linq C#

Below is the statement in question. It keeps throwing an exception saying "input string was not in the correct format"

totalAmount = QDL.Document.Totals.Total.Sum(s => decimal.Parse(s.valueTotal));

My totalAmount variable is of a decimal type and "Total" is a list of containing valueTotal which is also of a string data type.

One constraint is that my valueTotal HAS to be of string data type (that cannot change) and it has to write the sum of all those totals to totalAmount which has to be of decimal data type.

PLEASE HELP!

UPDATE: Implemented the following as suggested by Styx in the comments:

totalAmount = QDL.Document.Totals.Total.Sum(s => { decimal result; Decimal.TryParse(s.valueTotal, NumberStyles.None, CultureInfo.InvariantCulture, out result); return result; });

It now just keeps returning zero and not Parsing my string. see the screenshot below taken during debugging:

Debugging Value

Upvotes: 0

Views: 1719

Answers (2)

Nick Weidemann
Nick Weidemann

Reputation: 9

PROBLEM SOLVED!

Big thanks to @Styx for the answer.

The below implementation worked perfectly as needed:

totalAmount = QDL.Document.Totals.Total.Sum(s => 
    { 
        decimal result;
        Decimal.TryParse(s.valueTotal, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result);
        return result; 
    });

Thanks again.

Upvotes: 1

Rahul
Rahul

Reputation: 77846

You can use TryParse() like

QDL.Document.Totals.Total.Sum(s => 
                 decimal.Tryparse(s.valueTotal, out decimal val)
                 ? val : 0);

Upvotes: 1

Related Questions