c# - TryParse failing with negative numbers -
i'm having problem getting tryparse work correctly me. have list of values assured valid (as come component in our system) make sure there proper error handling in place.
here example list of values:
20.00
20.00
-150.00
and here method wrote:
private decimal calculatevalue(ienumerable<xelement> summaryvalues) { decimal totalvalue = 0; foreach (xelement xelement in summaryvalues) { decimal successful; decimal.tryparse(xelement.value, out successful); if (successful > 0) totalvalue += decimal.parse(xelement.value); } return totalvalue; }
the variable 'successful' returning false -150.00, added numberstyles:
private decimal calculatevalue(ienumerable<xelement> summaryvalues) { decimal totalvalue = 0; foreach (xelement xelement in summaryvalues) { decimal successful; decimal.tryparse(xelement.value, numberstyles.allowleadingsign, null, out successful); if (successful > 0) totalvalue += decimal.parse(xelement.value, numberstyles.allowleadingsign); } return totalvalue; }
however, have numberstyles in there, none of numbers parse! feel having iformatprovider set null within our system. see may doing wrong?
the other answers have got right idea regard proper way use decimal.tryparse
. however, if writing method in question, i'd use linq work 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 version works exact same way, uses enumerable.sum method calculate total. have supply inline function extracts decimal values xelement.
Comments
Post a Comment